【发布时间】:2021-02-18 11:19:18
【问题描述】:
import React from 'react';
import {GoogleMap, useLoadScript, Marker, InfoWindow} from '@react-google-maps/api';
import usePlacesAutocomplete, {getGeocode, getLatLng} from 'use-places-autocomplete';
import {Combobox, ComboboxInput, ComboboxPopover, ComboboxList, ComboboxOption} from "@reach/combobox";
import "@reach/combobox/styles.css";
import './App.css';
const libraries = ['places']
const mapContainerStyle = {
width: '72vw',
height: '100vh',
}
const options = {
disableDefaultUI: true,
zoomControl: true,
}
const center = { lat: 55.70927, lng: 9.5357 }
export default function App() {
const {isLoaded, loadError} = useLoadScript({
googleMapsApiKey: 'AIzaSyBRFI4qwdgva4fCSjZud-VLcXXywHYwAa4',
libraries,
})
const [markers, setMarkers] = React.useState([])
const onMapClick = React.useCallback((event) => {
setMarkers(current => [
...current,
{
lat: event.latLng.lat(),
lng: event.latLng.lng(),
time: new Date(),
},
]);
}, []);
const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);
const panTo = React.useCallback(({lat, lng}) => {
mapRef.current.panTo({lat, lng});
mapRef.current.setZoom(14);
}, []);
if(loadError) return 'Error loading maps'
if(!isLoaded) return 'Loading Maps'
return (
<div>
<Locate panTo={panTo}/>
<GoogleMap
mapContainerStyle={mapContainerStyle}
zoom={13}
center={center}
onClick={onMapClick}
onLoad = {onMapLoad}
options={options}
>
{markers.map((marker) => (
<Marker
key={marker.time.toISOString()}
position = {{
lat: marker.lat,
lng: marker.lng
}}
icon = {{
url: '/food.png',
scaledSize: new window.google.maps.Size(20,20),
origin: new window.google.maps.Point(0,0),
anchor: new window.google.maps.Point(10,10)
}}
/>
))}
</GoogleMap>
<section id="sidebar">
<h5 className="tc">Restaurant Review</h5>
</section>
</div>
);
}
function Locate({panTo}) {
return(
<button className="locate" onClick={() => {
navigator.geolocation.getCurrentPosition((position) => {
panTo({
lat: position.coords.latitude,
lng: position.coords.longitude,
})
}, () => null, options);
}}>
click
</button>
)
}
我想用标记在 Google 地图上显示我所在区域的场地,但我还需要在页面加载时显示用户位置。我创建了一个函数,但仅在用户单击按钮时才起作用。我是 React 和 JavaScript 的新手,不知道自己在做什么。
【问题讨论】:
标签: javascript reactjs google-maps geolocation