Google Places photos getUrl() is breaking my javascript

Rory picture Rory · Mar 17, 2014 · Viewed 7.6k times · Source

I have the following javascript:

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      place = new Object ({
        name: results[i].name,
        photo: results[i].photos[0].getUrl({'maxWidth': 100, 'maxHeight': 100}),
        loc: results[i].geometry.location,
        rating: results[i].rating,
      })
      places.push(place);
      var marker = new google.maps.Marker({
        map: map,
        position: results[i].geometry.location,
        id: i,
        visible: false,
      });
      markers.push(marker);
    }
  }
  newresult();
}

If i comment out the following line the function newresult() will run:

photo: results[i].photos[0].getUrl({'maxWidth': 100, 'maxHeight': 100}),

However, as in the above code, if i do not comment it out the function newresult() will not run. I know that the getUrl function of photo works as it returns a valid url.

Thanks for any help.

Answer

davidkonrad picture davidkonrad · Mar 17, 2014

I know that the getUrl function of photo works as it returns a valid url.

Yes, IF there is a photo associated with the place! No photo for a place = no photo array in the results[i] object. And then your code breaks. You must in each iteration check if the photo array is present before using it :

place = new Object ({
   name: results[i].name,
   photo: typeof results[i].photos !== 'undefined' 
       ? results[i].photos[0].getUrl({'maxWidth': 100, 'maxHeight': 100})
       : '' //alternative a "nophoto.jpg"
   loc: results[i].geometry.location,
   rating: results[i].rating,
});

Here a fiddle based on your code from above -> http://jsfiddle.net/dX9Gu/