我试图建立一个应用程序,有一个地图,每次用户点击地图,该动作应该在那个点上留下一个标记,但如果他点击不止一次,那应该在这些坐标之间创建一个折线,如果他右键点击他做的一个标记,该标记之后的一切都应该被删除。好吧,我有实现添加这些标记和折线的问题,我使用@react-google-maps/api版本^2.17.1和反应^18.2.0。我尝试在使用组件中的onClick方法之前在一个数组上使用useEffect,该数组持有添加的坐标,但没有任何显示,该数组根本没有事件改变。我在Youtube和谷歌上搜索了很多,看看我是否能找到@react-google-maps/api的教程,但没有运气。
这是我的地图。jsx文件:import React from 'react'
import {GoogleMap, Marker, Polyline, useJsApiLoader} from '@react-google-maps/api'
import * as key from '../../constants/actions';
import { useEffect, useState } from 'react';
const Map = () => {
let coordinates = [];
const { isLoaded } = useJsApiLoader({
id:'google-map-script',
googleMapsApiKey: key.MAPS_API_KEY
})
const [map, setMap] = React.useState(null)
const onLoad = React.useCallback(function callback(map) {
const bounds = new window.google.maps.LatLngBounds(center);
// map.fitBounds(bounds);
setMap(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
setMap(null)
}, [])
const containerStyle ={
width:'100vw',
height:'100vh',
background:'green'
}
const center = {
lat: 44.087585,
lng: -39.899556
}
const onLoadMarker = marker => {
console.log('marker: ', marker)
}
const onLoadPoly = polyline => {
console.log('polyline: ', polyline)
};
const options = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
clickable: false,
draggable: false,
editable: false,
visible: true,
radius: 30000,
paths: coordinates,
zIndex: 1
};
return isLoaded ? (
<div style={{padding:'10px'}}>
<GoogleMap mapContainerStyle={containerStyle}
center={center}
zoom={3}
onLoad={onLoad}
onUnmount={onUnmount}
onClick={(e) => {
coordinates.push({lat:e.latLng.lat(), lng: e.latLng.lng});
<Marker position={{lat:e.latLng.lat(), lng: e.latLng.lng}} onLoad={onLoadMarker}/>;
<Polyline path={coordinates} options={options} onLoad={onLoadPoly} />
}}
>
</GoogleMap>
</div>
) : <></>
}
export default Map
我将感激任何帮助。谢谢你!
我试着复制你的代码,并使它以某种方式工作。我注意到你正试图将新的标记推到一个数组中,但这不是它在React中的工作方式。你需要利用State Hooks
和map
方法来修改你的数组和更新你的谷歌地图地图,当你点击它。这里有一些参考资料,可能会对你未来的努力有所帮助:
更新状态
中的数组了解ReactJS中的Map
现在看看它是如何编码的,这里是你需要的State钩子:
// Hook for center
// This hook is used for updating
// the center whenever you click on the map
const [center, setCenter] = React.useState({
lat: 44.087585,
lng: -39.899556
});
// Hook for polyline path
// This is an array used for storing
// the sequence of your clicks which
// will be used later on when double clicking
// the map to render the polyline.
const [path, setPath] = React.useState([]);
// This array is where the path sequence
// will be stored once you
// double click any marker.
const [loadPolyline, setLoadPolyline] = React.useState([]);
// Hook for the location per click on the MAP
// This is the where the location of your
// click is stored which is the data used
// for rendering your Marker, this is an
// array and is updated each click.
const [location, setLocation] = React.useState({
markers: [
{
title: "The marker`s title will appear as a tooltip.",
name: "",
position: null
}
]
});
下面是函数:
// Function when clicking on the MAP
// This is the function that updates
// the location hook array that will
// store new markers on click.
const mapClicked = (e) => {
const lat = e.latLng.lat();
const lng = e.latLng.lng();
const markerLoc = { lat: lat, lng: lng };
const markerCoordinate = `lat: ${lat} lng: ${lng}`;
setPath((previousState) => [...previousState, { lat: lat, lng: lng }]);
setCenter({ lat: lat, lng: lng });
setLocation((previousState) => {
return {
markers: [
...previousState.markers,
{
title: "",
name: markerCoordinate,
position: markerLoc
}
]
};
});
};
// handle rightclick
// This is a function that will reset
// your locations, path, polyline arrays
// which will remove all
// stored and rendered markers/polyline.
const handleRightClick = () => {
setLocation({
markers: [
{
title: "The marker`s title will appear as a tooltip.",
name: "",
position: null
}
]
});
setLoadPolyline([]);
setPath([]);
};
//handle doubleclicks
const handleDoubleClick = (e) => {
setLoadPolyline(path);
};
下面是你的<GoogleMap>
组件的样子:
//Loads the MAP
return isLoaded ? (
<div style={{ padding: "10px" }}>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={3}
onLoad={onLoad}
onUnmount={onUnmount}
onClick={mapClicked}
>
{<!--Here's the map method for your markers array-->}
{location.markers.map((markers, key) => (
<Marker
icon={"https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png"}
key={key}
title={markers.title}
name={markers.name}
position={markers.position}
onRightClick={handleRightClick}
onDblClick={handleDoubleClick}
>
</Marker>
))}
<Polyline path={loadPolyline} options={options} />
</GoogleMap>
</div>
) : (
<></>
);
这里有一个关于codesanbox的概念证明供您尝试。
注:折线似乎偏离了标记,我已经在墙上撞了很长一段时间试图修复它。
但是,希望这对你有帮助!