Попытка найти близлежащие места в API мест Google - PullRequest
0 голосов
/ 11 февраля 2019

Я запускаю сценарий Javascript для поиска ближайшего арендного хранилища пользователя, но постоянно получаю эту ошибку:

ReferenceError: google is not defined

Несмотря на то, что я специально импортирую API-интерфейс карты Google в свой код.Вот мой код:

<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 голосов
/ 11 февраля 2019

Вы загружаете API Google Maps Javascript асинхронно (с async defer).API не будет доступен (google будет неопределенным), пока не завершится загрузка.В это время он запустит вашу функцию обратного вызова (initMap).

Описания в документации API:

Код внутри функции find зависит от загружаемого JavaScript API Google Maps v3.Переместите вызов функции find() в initMap (или загрузите API синхронно).

Примечание: у вас также есть опечатка, после внесения этого изменения я получаю ошибку javascript: google.maps.places.PlaceServices is not a constructor, должно быть google.maps.places.PlacesService, затем ReferenceError: callback is not defined (поскольку оно не определено)

подтверждение концепции скрипта

фрагмент кода: (обратите внимание, карта не инициализируется из-за песочницы)

#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>
...