首页 > 解决方案 > Anonymous function error on Google Maps API marker click

问题描述

Using Foursquare Google Maps APIs, my goal is to use the venue photo property provided by Foursquare and, if it's available in a venue's metadata, to render it along with the venue's name within the Google Maps API info window. If only one of the two properties are available, I want to render the available one only. If the venueInfo is undefined or neither property is available, I want to simply display "No info available" in the info window. I tried doing this with a conditional operator with multiple conditions.

For at least one marker, sometimes the info will display, but sometimes I get these errors.

enter image description here

I don't understand what's wrong or how to fix it. If the 'name' property is undefined, shouldn't the conditional just make it fall back to display "No info available"? And if the info for the marker displayed fine previously, how can it stop working when I click the same marker again?

Here's my conditional statement for rendering inside the info window:

            <InfoWindow>
        {venueInfo.name && venueInfo.bestPhoto ?
          <Fragment>
            <p>{venueInfo.name}</p>
            <img src={`${venueInfo.bestPhoto.prefix}200x200${venueInfo.bestPhoto.suffix}`}
            alt={"Venue"}
            />
          </Fragment> : venueInfo.name ? <p>{venueInfo.name}</p> : venueInfo && venueInfo.bestPhoto ? <img    src={`${venueInfo.bestPhoto.prefix}200x200${venueInfo.bestPhoto.suffix}`}
          // Screen readers already announce as image; don't need the word "image", "photo", etc.
          alt={"Venue"}
        /> : <p>No info available</p>}
      </InfoWindow>

For reference here's the full component code on GitHub.

标签: javascriptreactjsgoogle-maps-api-3foursquare

解决方案


The error you get is caused by trying to access a property of a value which is undefined.

What that means in your case is that venueInfo is actually undefined when trying to access venuInfo.bestPhoto. Which would cause the crash and not the conditional operator.


推荐阅读