【发布时间】:2020-06-17 18:53:19
【问题描述】:
在实现 google maps api 时,我不断收到以下错误。我一直在关注 youtube 教程,并且一直在将其调整为我的代码。两个主要问题首先是地图属性未定义。第二个是我不确定我的 google api url 是否为 mapData 正确提取。任何帮助将不胜感激。
×
TypeError: Cannot read property 'map' of undefined
Map
C:/Users/Langley/Desktop/ArticCards/screens/MapScreen.js:18
15 | const [selectedSpeech, setSelectedSpeech] = useState(null);
16 |
17 | return(
> 18 | <GoogleMap
| ^ 19 | defaultZoom={10} defaultCenter={{lat: 42.807091, lng: -86.018860}}
20 | >
21 | {mapData.results.map((speech) => (
地图屏幕
import React, { useState, useEffect } from "react";
import {
withGoogleMap,
withScriptjs,
GoogleMap,
Marker,
InfoWindow
} from "react-google-maps";
import {getMap} from '../api/gmap';
import {gkey} from '../api/gkey'
const mapData = getMap();
function Map(){
const [selectedSpeech, setSelectedSpeech] = useState(null);
return(
<GoogleMap
defaultZoom={10} defaultCenter={{lat: 42.807091, lng: -86.018860}}
>
{mapData.results.map((speech) => (
<Marker key={speech.place_id} position={{
lat: speech.geometry.location.lat,
lng: speech.geometry.location.lng
}}
onPress={() => {
setSelectedSpeech(speech);
}}
/>
))}
{selectedSpeech && (
<InfoWindow position={{
lat: selectedSpeech.geometry.location.lat,
lng: selectedSpeech.geometry.location.lng
}}
onCloseClick={() => {
setSelectedSpeech(null);
}}
>
<div>
<h2>
{selectedSpeech.name}
</h2>
<h3>
{selectedSpeech.rating}
</h3>
<p>
{selectedSpeech.formatted_address}
</p>
</div>
</InfoWindow>
)}
</GoogleMap>
);
}
const WrappedMap = withScriptjs(withGoogleMap(Map));
const MapScreen = () => {
return(
<div style={{width: '100vw', height: '100vh'}}>
<WrappedMap googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${gkey}`}
loadingElement = {<div style={{height: "100%"}}/>}
containerElement = {<div style={{height: "100%"}}/>}
mapElement = {<div style={{height: "100%"}}/>}
/>
</div>
)
}
export default MapScreen;
gmap.js
import axios from 'axios'
import {gkey} from './gkey';
const gmapServer = axios.create({
baseURL:'http://maps.googleapis.com/'
})
export const getMap = async (callback) => {
const response = await gmapServer.get(
`maps/api/place/textsearch/json?query=speech+pathologists&key=${gkey}`
);
callback(response.data)
};
【问题讨论】:
-
执行
const mapData = getMap(); console.log(mapData)并检查您实际得到的结果,因为它不包含具有results属性的对象 -
在运行应用程序时进入该屏幕的唯一方法是删除地图部分。当我这样做时,我看不到控制台中加载任何内容。我尝试使用 const mapData = //url 代替,但仍然没有。我现在很茫然。
标签: javascript reactjs google-maps google-places-api