Each API works individually, but together they don't

时间:2016-04-21 21:59:04

标签: google-maps google-maps-api-3 google-api

When using location Google autocompletion API with this code just before </body>, it works:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
<script>
    var input = document.getElementById('where');
    var autocomplete = new google.maps.places.Autocomplete(input);
</script>

When using this Google map API code just before </body>, it works too :

<script src="https://maps.googleapis.com/maps/api/js" async defer></script>
<script>
function initMap() {
  var myLatLng = {lat: 47.901773, lng: 1.905062};
  var map = new google.maps.Map(document.getElementById('map'), { center: myLatLng, scrollwheel: false, zoom: 12 });
  var marker = new google.maps.Marker({map: map, position: myLatLng, title: 'Hello World!'});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>

But when using both of them, one after another, the autocompletion code doesn't work anymore. Why?

1 个答案:

答案 0 :(得分:1)

Don't load the Google Maps Javascript API multiple times. Only load it once, combining all the parameters and libraries in the single line (per the documentation). If you are loading it asynchronously (with a callback), all the code that depends on the API must be in the callback function, so it doesn't execute until the API has completely loaded (which is when the callback function runs).

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

code snippet:

function initMap() {
  var myLatLng = {
    lat: 47.901773,
    lng: 1.905062
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    center: myLatLng,
    scrollwheel: false,
    zoom: 12
  });
  var marker = new google.maps.Marker({
    map: map,
    position: myLatLng,
    title: 'Hello World!'
  });
  var input = document.getElementById('where');
  var autocomplete = new google.maps.places.Autocomplete(input);
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<input id="where" />
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>

相关问题