当我更改地图的位置时,它会返回到其原始位置。如何消除这种行为?我需要在更改地图位置时,地图保持在相同位置。
错误行为GIF https://gyazo.com/4fa3cf138ceacc1ffdb4cb9055f8b8f3
<Map
dragRotate={false}
scrollZoom={true}
zoom={[15]}
center={[23.924760, 54.930400]}
style="mapbox://styles/mapbox/streets-v9"
containerStyle={{
height: "500px",
width: "100wv"
}}>
<ZoomControl/>
<a href='https://goo.gl/maps/kPEmoBpFUPL2' className='link-primary map-link' target='_blank'>Directions</a>
<Layer
type="symbol"
id="marker"
layout={{ "icon-image": "harbor-15" }}>
<Feature
coordinates={[23.925960, 54.930854]}
/>
</Layer>
</Map>
答案 0 :(得分:1)
您还可以使用 useState 钩子将 center 和 zoom 道具绑定到一个状态,这样无需使用它们即可使其保持不变。更新每次互动的价值。请参阅:https://github.com/alex3165/react-mapbox-gl/issues/81
我发现的唯一缺点是,您需要将缩放包装在数组上以保持相等...
const [center, setCenter] = useState<[number, number]>([-94.239, 36.066]);
const [zoom, setZoom] = useState<[number]>([11]);
...
<Map
style="mapbox://styles/mapbox/streets-v11"
center={center}
zoom={zoom}
>
...
答案 1 :(得分:0)
当用户移动地图时,您只需要更新地图状态即可记录新的地图位置(纬度/经度,缩放...)。例如:
import React from 'react'
import ReactDOM from 'react-dom'
import mapboxgl from 'mapbox-gl'
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA';
class Application extends React.Component {
constructor(props: Props) {
super(props);
this.state = {
lng: 5,
lat: 34,
zoom: 1.5
};
}
componentDidMount() {
const { lng, lat, zoom } = this.state;
const map = new mapboxgl.Map({
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v9',
center: [lng, lat],
zoom
});
map.on('move', () => {
const { lng, lat } = map.getCenter();
this.setState({
lng: lng.toFixed(4),
lat: lat.toFixed(4),
zoom: map.getZoom().toFixed(2)
});
});
}
render() {
const { lng, lat, zoom } = this.state;
return (
<div>
<div className="inline-block absolute top left mt12 ml12 bg-darken75 color-white z1 py6 px12 round-full txt-s txt-bold">
<div>{`Longitude: ${lng} Latitude: ${lat} Zoom: ${zoom}`}</div>
</div>
<div ref={el => this.mapContainer = el} className="absolute top right left bottom" />
</div>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
有关完整示例,请查看其basic boilerplate on Github。