Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to call google initMap callback function outside the google API URL?

I am using google map API which contain initMap callback function, I need to call this function outside the google map API URL for example I am using:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"></script>

I need to remove last part of query string &callback=initMap but when I remove google map does not work.

Problem is I want to use this same google map api for all google api related stuff hence some APIs does not have initMap method thats why I want to call this method separably is it possible.

like image 446
Kamran Khatti Avatar asked Oct 23 '25 16:10

Kamran Khatti


1 Answers

You don't have to call the initMap function asynchronously.

Change (looks like it is missing the "async defer"):

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"></script>

To:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Then call the initMap function after the map div has been rendered in the DOM.

Note: there is a reason that Google has changed all their examples to asynchronously load the API (page load speed), all their examples were originally done with an onload function.

code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
like image 168
geocodezip Avatar answered Oct 25 '25 05:10

geocodezip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!