Google Places API开发出现TypeError: Cannot read properties of undefined (reading 'location')错误,求原因解析
Hey there, let's break down why you're hitting this error with the Google Places API. First, let's recap the issue you're seeing:
TypeError: Cannot read properties of undefined (reading 'location')
错误堆栈:ur.onPlaceChanged http://localhost:3000/static/js/main.chunk.js:82:49
Here's the relevant code snippet:
79 | const onLoad = autoC => setAutocomplete(autoC); 80 | 81 | const onPlaceChanged = () => { > 82 | const lat = autocomplete.getPlace().geometry.location.lat(); | ^ 83 | const lng = autocomplete.getPlace().geometry.location.lng(); 84 | setCoords({ 85 | lat,
What's causing this?
This error means when your code tries to access .location, the geometry property above it is undefined. There are a few common culprits:
- User didn't select a valid place: If the user types text into the autocomplete field but doesn't pick a suggestion from Google's dropdown list,
getPlace()returns an object missing thegeometryproperty entirely. - Autocomplete instance isn't ready: If
onPlaceChangedfires before theautocompletestate is properly set viasetAutocomplete, eitherautocompleteitself could be undefined, orgetPlace()returns an incomplete object. - API configuration issues: If your Google Places API isn't enabled in the Cloud Console, or your API key lacks the right permissions (or hits quota limits), the returned place data might omit critical fields like
geometry.
How to fix this?
Let's walk through actionable solutions:
Add null/undefined checks to your code
Validate each layer of the object before accessing nested properties. Update youronPlaceChangedfunction like this:const onPlaceChanged = () => { const place = autocomplete.getPlace(); // Check if we have a valid place with complete geometry data if (!place || !place.geometry || !place.geometry.location) { alert("请从下拉列表中选择一个有效的地点哦"); return; } const lat = place.geometry.location.lat(); const lng = place.geometry.location.lng(); setCoords({ lat, lng }); };This stops your code from trying to access non-existent properties and gives clear feedback to the user.
Ensure the autocomplete instance is properly initialized
Double-check that youronLoadfunction triggers when the Google Places Autocomplete finishes loading. ConfirmsetAutocompletecorrectly updates your state variable soautocompleteisn't undefined whenonPlaceChangedruns.Verify your API setup
Head to the Google Cloud Console and confirm:- The Places API is enabled for your project
- Your API key has Places API access in its restrictions
- You haven't exceeded your daily API quota
内容的提问来源于stack exchange,提问作者KOTISWAR

