Vasudev Gupta
Vasudev Gupta

Reputation: 89

Trying to find nearby places in Google places API

I am running a Javascript script to find the User's nearest Rental Storage Unit, but I keep getting this error:

ReferenceError: google is not defined

Even though I specifically import the google map's API in my code. Here is my code:

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

Upvotes: 1

Views: 3953

Answers (1)

geocodezip
geocodezip

Reputation: 161334

You are loading the Google Maps Javascript API asynchronously (with async defer). The API won't be available (google will be undefined) until it finishes loading. At that time it will run your callback function (initMap).

Descriptions in the API documentation:

The code inside the find function depends on the Google Maps Javascript API v3 being loaded. Move the call of the find() function call inside initMap (or load the API synchronously).

Note: you also have a typo, once I make that change, I get the javascript error: google.maps.places.PlaceServices is not a constructor, should be google.maps.places.PlacesService, then ReferenceError: callback is not defined (because it isn't defined)

proof of concept fiddle

code snippet: (note, doesn't initialize map due to sandboxing)

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

Upvotes: 2

Related Questions