Question

I'm trying to retrieve place details using the Google Places Library. When you click the place marker I want to be able to see the address, name, website etc.

I'm using the following tutorial: http://code.google.com/apis/maps/documentation/javascript/places.html

All seems to be going pretty well. In my marker I can display the name and the rating but the address, website and phone number all appear as 'undefined'. Is this because Google doesn't have the information I'm requesting on these places? Or have I done something wrong?

Here's the code I'm using: var map; var infowindow;

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

    map = new google.maps.Map(document.getElementById('map_canvas'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: pyrmont,
      zoom: 15
    });

    var request = {
      location: pyrmont,
      radius: 5000,
      types: ['bar']
    };
    infowindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(place.name + "<br />" + place.formatted_address +"<br />" + place.website + "<br />" + place.rating + "<br />" + place.formatted_phone_number);
      infowindow.open(map, this);
    });
  }

Any help or ideas will be greatly appreciated.

Cheers.

JA

Was it helpful?

Solution

You're doing a Place Search, which doesn't return all of the fields that you're using:

http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses

In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference. See:

http://code.google.com/apis/maps/documentation/javascript/places.html#place_details_requests

Roughly, your code would change to:

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    var request = { reference: place.reference };
    service.getDetails(request, function(details, status) {
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
        infowindow.open(map, this);
      });
    });
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top