Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load google map without using callback method

i have multiple google map instances on my website,now there are two different google map on a same page, what happens is the first one works and other doesn't now i know the logical issue let me show you my code first

<script>
    function initMap() {
        var myLatLng = {lat: 43.6222102, lng:-79.6694881};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: myLatLng
        });

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=my_key&callback=initMap"
        async defer></script>

now as i defined a callback method it always initializes the method named initMap whereas what i want to do is there can be multiple google maps lets suppose initMap2 how can i load them without callback method?

like image 741
uneeb meer Avatar asked Jun 20 '17 17:06

uneeb meer


People also ask

Can I use Google Maps without API?

If you use Elementor on your website you can also add Google Map without api key. In order to embed a Google Map iframe without api key add a Google Map widget from the left side panel. Then open it and add the address. This way you can embed Google Map without api key via Elementor.

Can I put Google Maps on my site without using Google Maps platform products?

Yes. Google Maps now offers the ability to embed the map that you're viewing into your website or blog, without any programming or use of the Google Maps Platform.

Can I use Google Maps without billing?

With Google Maps Platform flexible pricing, daily quotas, and 28,500 maploads per month for no charge, it's easy to stay on budget.


1 Answers

To load the map without a callback, load the API synchronously/inline (without the async defer), then call your initMap function on the load event.

(Note: FYI: Google changed all their examples to using asynchronous loading to improve the load times)

(Note2: Google has added a "sample" to their documentation describing synchronous loading)

proof of concept fiddle

code snippet:

function initMap() {
  var myLatLng = {
    lat: 43.6222102,
    lng: -79.6694881
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
  });
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
like image 176
geocodezip Avatar answered Nov 07 '22 22:11

geocodezip