How to modify existing working WP site which is using Goole Maps Javascript API to use a Key?

302 views Asked by At

Context

I've inherited a legacy working WP site which is uses Google Maps JavaScript API. As API key is now mandatory the maps displayed correctly, but popup error says 'This page can't load Google Maps correctly' and maps are grayed and disabled

What I've done so far

Key

I registered and now I have my key and it is enabled for Maps JavaScript API and also enabled for the site. (actually not restricted yet, first I would like to see the code working, then I am going to restrict)

Source

(Disclamer: WP and PHP newbie here sorry, at least JavaScript OK)

  • I examined the existing source, and concluded it uses the Maps JavaScript API. It seems to be not the newest of course
  • I looked for Google Docs and found this:

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script> it seems to be clear

  • I read the WP docs about wp_register_script and wp_enqueue_script it seems to be clear.

Question

Despite of this foreplay, I still have no idea what and how should be modified. The actual lines I found in the existing source:

wp_register_script( 'google-maps-api', esc_url( add_query_arg( array( 'v' => 3, 'sensor' => 'false' ), is_ssl() ? 'https://maps-api-ssl.google.com/maps/api/js' : 'http://maps.google.com/maps/api/js' ) ), array(), VERSION, true );
...
...
wp_enqueue_script( 'google-maps-api' );

The javascript urls seems to be a bit different than what I found in the current Google documentation

I do not know if I should modify this urls to add the key parameter (those older urls accept the Key= parameter?) or I should add a new register script with exactly that url what the current google docs say (and also leave the old ones?) I do not know how to register a script url with parameters (key).

1

There are 1 answers

0
zipkundan On BEST ANSWER

Try:

Comment out the code lines which enqueue script with old ULR of google maps api.

Use following lines to enqueue google maps api new script (with new URL).

wp_register_script( 'google-maps-api', esc_url( add_query_arg( array('key'=>'YOUR_API_KEY', 'callback'=>'initMap'), 'https://maps.googleapis.com/maps/api/js' ) ), array(), VERSION, true );
wp_enqueue_script( 'google-maps-api' );

Replace 'YOUR_API_KEY' with actual value of api key.

Hope this will work for you. Please let me know.