jonny-harte
jonny-harte

Reputation: 339

Center google Map on place ID without specifying lat and long?

How do you center a google map based on a placeID, without setting the lat and lng explicitly in the map object?

All examples I've seen have a value set e.g.

var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

Form: developers.google.com

Surely you can getDetails on a place based on an ID, then use the lat and lng to center the map?

function initializeGoogleMaps() {
  jQuery('.site-content').prepend('<div id=\"map-container\"><div id=\"map-canvas\"></div></div>');

  var request = {
    placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
  };

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
    }
  }

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 51.509526,
      lng: -0.156314
    },
    zoom: 15
  });

  service = new google.maps.places.PlacesService(map);
  service.getDetails(request, callback);
}

Upvotes: 3

Views: 4357

Answers (1)

geocodezip
geocodezip

Reputation: 161384

You can set the center of the map using the value returned from the places service (or the position of the marker):

proof of concept fiddle

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      map.setCenter(marker.getPosition());
    }
  }

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

code snippet:

function initializeGoogleMaps() {
  var request = {
    placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
  };

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      map.setCenter(marker.getPosition());
    }
  }

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

  service = new google.maps.places.PlacesService(map);
  service.getDetails(request, callback);
}
google.maps.event.addDomListener(window, 'load', initializeGoogleMaps);
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map-canvas"></div>

Upvotes: 6

Related Questions