gpt4 book ai didi

javascript - 如何将 react-leaflet map 定位到用户的当前位置并获取该 map 的边框?

转载 作者:行者123 更新时间:2023-12-05 00:31:10 26 4
gpt4 key购买 nike

我需要将 react-leaflet map 定位到用户的当前位置并获取该 map 的边框。我尝试应用以下代码,但遇到了错误:

TypeError: Cannot read property 'locate' of undefined (anonymousfunction)


请帮我!
import React, { useState, useEffect, useRef } from 'react';
import restaurantsInfo from "./RestaurantsList.json";
import "./App.css";
import { MapContainer, Marker, Popup, TileLayer, useMapEvents } from "react-leaflet";
import { Icon, latLng } from "leaflet";
import Restaurants from "./Restaurants.js";
import LocationMarker from "./LocationMarker.js";
import L from 'leaflet';

const myLocation = [49.1951, 16.6068];
const defaultZoom = 13;

export default function App() {

const mapRef = useRef();
useEffect(() => {
const { current = {} } = mapRef;
const { leafletElement: map } = current;
map.locate({
setView: true,
});
map.on('locationfound', handleOnLocationFound);
}, []);

function handleOnLocationFound(event) {
const { current = {} } = mapRef;
const { leafletElement: map } = current;
const latlng = event.latlng;
const radius = event.accuracy;
const circle = L.circle(latlng, radius);
circle.addTo(map);
}

return (
<div class="container">
<div style={{height: '400px', width: '500px'}} class="map">

<MapContainer ref={mapRef} center={myLocation} zoom={defaultZoom} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
< /MapContainer >

最佳答案

您需要一个自定义组件来完成这项工作,并且是 MapContainer 的子组件.从 locationfound 获取边界框event.bounds

 function LocationMarker() {
const [position, setPosition] = useState(null);
const [bbox, setBbox] = useState([]);

const map = useMap();

useEffect(() => {
map.locate().on("locationfound", function (e) {
setPosition(e.latlng);
map.flyTo(e.latlng, map.getZoom());
const radius = e.accuracy;
const circle = L.circle(e.latlng, radius);
circle.addTo(map);
setBbox(e.bounds.toBBoxString().split(","));
});
}, [map]);

return position === null ? null : (
<Marker position={position} icon={icon}>
<Popup>
You are here. <br />
Map bbox: <br />
<b>Southwest lng</b>: {bbox[0]} <br />
<b>Southwest lat</b>: {bbox[1]} <br />
<b>Northeast lng</b>: {bbox[2]} <br />
<b>Northeast lat</b>: {bbox[3]}
</Popup>
</Marker>
);
}
在这里使用它
<MapContainer
center={[49.1951, 16.6068]}
...
<LocationMarker />
</MapContainer>
Demo

关于javascript - 如何将 react-leaflet map 定位到用户的当前位置并获取该 map 的边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66500181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com