MilkACow
MilkACow

Reputation: 67

Uncaught TypeError: Cannot read property 'length' of undefined Google Map V3

I know this been asked a tons of time, but I can't seem to find the correct answer to my problem.

Its actually very straight forward:

service.getDetails(request, function(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {

Was used prior to using getDetails on its photos, so we know it actually fetches non-empty data. Next,

for (var i = 0; i < place.photos.length; i++) {
    ....
}

Afterwards I used photos length.

Please NOTE: It works fine, UNLESS the place actually has NO pictures to pull.... now it is throwing it off with the "Uncaught TypeError: Cannot read property 'length' of undefined".

Is there a condition I can put prior to calling the place.photos.length so I can eliminate this error message?

Thanks for reading! Please help out.

Upvotes: 1

Views: 2285

Answers (1)

Pointy
Pointy

Reputation: 414036

Simply check that place.photos exists first:

if (place.photos)
  for (var i = 0; i < place.photos.length; i++) 
    // ...

With that if check, if place.photos is null or undefined (probably undefined is the most likely, as your error indicates) then the loop won't be attempted.

Upvotes: 2

Related Questions