7

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.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Rory
  • 220
  • 3
  • 10
  • what is `results`? It isn't clear from your code how you're calling this callback function... this is in response to what exactly? – duncan Mar 17 '14 at 16:38
  • 1
    also are you sure your photos array has length? What happens if you set a variable to the results of `results[i].photos[0].getUrl({'maxWidth': 100, 'maxHeight': 100})`, which you then add to your 'place' object? – duncan Mar 17 '14 at 16:50
  • Do you get any javascript errors? – geocodezip Mar 17 '14 at 17:07
  • how do you use this function(for which method it will be used as callback?) – Dr.Molle Mar 17 '14 at 18:19

1 Answers1

15

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/

davidkonrad
  • 83,997
  • 17
  • 205
  • 265