尝试在Google Places API中找到附近的地方

时间:2019-02-11 14:09:54

标签: javascript html google-maps google-places-api

我正在运行一个Javascript脚本来查找用户最近的租赁存储单元,但是我不断收到此错误:

ReferenceError: google is not defined

即使我在代码中专门导入了Google Map的API。 这是我的代码:

<html>
<style>
    #map{
        width: 100%;
        height:100%;
    }
</style>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=
AIzaSyByYsxs4EycWo0hRKr6deRs1A5Wo9niOZ4&callback=initMap"
async defer></script>
<script>
function find(){
  var request = {
    types: ['Storage Units']
  };
  infowindow = new google.maps.InfoWindow();
  places = new google.maps.places.PlaceServices(map);
  places.nearbySearch(request, callback);
}
find()
function initMap(){
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
  });
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      map.setCenter(initialLocation);
      // creates a marker of user's location
      var marker = new google.maps.Marker({
        position: initialLocation,
        map:map,
        title:'Your Location'
      });
    });
  }
}
</script>    
</html>

1 个答案:

答案 0 :(得分:1)

您正在异步加载Google Maps Javascript API(使用async defer)。该API在加载完成之前将不可用(google是未定义的)。届时它将运行您的回调函数(initMap)。

API文档中的描述

find函数中的代码取决于所加载的Google Maps Javascript API v3。将find()函数调用的调用移到initMap内(或同步加载API)。

注意:您也有一个错字,一旦我进行了更改,我将收到JavaScript错误:google.maps.places.PlaceServices is not a constructor,应为google.maps.places.PlacesService,然后为ReferenceError: callback is not defined(因为未定义) )

proof of concept fiddle

代码段:(注意,由于沙箱操作,未初始化地图)

#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<div id="places"></div>
<script>
  var map;
  function find(latLng) {
    var request = {
      types: ['Storage Units'],
      location: latLng,
      radius: 10000
    };
    infowindow = new google.maps.InfoWindow();
    places = new google.maps.places.PlacesService(map);
    places.nearbySearch(request, callback);
  }

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 15,
      center: {lat: 40.713485, lng:-74.005063}
    });
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        map.setCenter(initialLocation);
        // creates a marker of user's location
        var marker = new google.maps.Marker({
          position: initialLocation,
          map: map,
          title: 'Your Location'
        });
        find(marker.getPosition());
      }, function(error) { console.log(error)
      });
    }
  }

  function callback(results, status, pagination) {
    if (status !== 'OK') return;

    createMarkers(results);
  };

  function createMarkers(places) {
    var bounds = new google.maps.LatLngBounds();
    var placesList = document.getElementById('places');

    for (var i = 0, place; place = places[i]; i++) {
      var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
      });

      var li = document.createElement('li');
      li.textContent = place.name;
      placesList.appendChild(li);

      bounds.extend(place.geometry.location);
    }
    map.fitBounds(bounds);
  }

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