我是 React 的新手,我正在尝试从外部数据库获取坐标以在谷歌地图上放置标记。我曾尝试使用 Fetch API 来获取坐标,但它返回一个承诺,因此地图在呈现之前不会获取坐标。我使用以下代码:
import React, { Component, useState } from "react";
import {
GoogleMap,
withScriptjs,
withGoogleMap,
Marker,
InfoWindow
} from "react-google-maps";
import Geocode from "react-geocode";
Geocode.setApiKey("API_KEY");
const WrappedMap = withScriptjs(withGoogleMap(Map));
const database_url_coordinates = "DATABASE_URL_COORDINATES";
function Map() {
Geocode.setApiKey("API_KEY");
Geocode.enableDebug();
const [selectedKalas, setSelectedKalas] = useState(null);
function Lat() {
return parseFloat(localStorage.getItem("user_lat"));
}
function Lng() {
return parseFloat(localStorage.getItem("user_lng"));
}
window
.fetch(database_url_coordinates)
.then(response => {
return response;
})
.then(data => {
return (
<GoogleMap
defaultOptions={{
streetViewControl: false,
minZoom: 5,
maxZoom: 15,
styles: [
{
featureType: "all",
elementType: "labels.text",
stylers: [
{
visibility: "off"
}
]
},
{
featureType: "poi",
elementType: "labels.icon",
stylers: [
{
visibility: "off"
}
]
}
]
}}
defaultZoom={13}
defaultCenter={{ lat: 63.418827, lng: 10.402732 }}
style={{ width: "100vw", height: "70vh" }}
>
<Marker
key={localStorage.getItem("kalas_id")}
position={{
lat: data[1].lat,
lng: data[1].lng
}}
icon={{
url:
"https://www.rr-a.no/wp-content/uploads/2018/01/map-marker-icon.png",
scaledSize: new window.google.maps.Size(50, 50)
}}
onClick={() => {
setSelectedKalas(localStorage.getItem("kalas_id"));
}}
/>
{selectedKalas && (
<InfoWindow
position={{
lat: Lat(),
lng: Lng()
}}
onCloseClick={() => {
setSelectedKalas(null);
}}
>
<div>
<h2>Ditt Kalas!</h2>
<p>Kalasnavn: {JSON.parse(localStorage.getItem("username"))}</p>
<p>
Kapasitiet: {JSON.parse(localStorage.getItem("capacity"))}
</p>
<p>
Adresse: {JSON.parse(localStorage.getItem("address"))},{" "}
{JSON.parse(localStorage.getItem("postal"))}
</p>
<p>
Telefonnr.: {JSON.parse(localStorage.getItem("phoneNumber"))}
</p>
</div>
</InfoWindow>
)}
</GoogleMap>
);
});
}
class MapClass extends Component {
constructor(props) {
super(props);
this.state = {
latiude: null,
longitude: null,
userAdress: null,
allMarkers: ""
};
}
render() {
return (
<div style={{ width: "100vw", heigth: "100vh" }}>
<WrappedMap
googleMapURL={
"https://maps.googleapis.com/maps/api/js?key=API_KEY&v=3.exp&libraries=geometry,drawing,places"
}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `70vh` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default MapClass;
我已经替换了 API_KEY 和 DATABASE_URL_COORDINATES。我得到的错误信息是:
Uncaught Error: Map(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
我将不胜感激任何反馈!