mirror of
https://github.com/visgl/react-map-gl.git
synced 2026-01-18 15:54:22 +00:00
58 lines
1.3 KiB
JavaScript
58 lines
1.3 KiB
JavaScript
import * as React from 'react';
|
|
|
|
import {useCallback, useState, useEffect} from 'react';
|
|
import {useMap} from 'react-map-gl';
|
|
|
|
export default function Controls() {
|
|
const {mymap} = useMap();
|
|
const [inputValue, setInputValue] = useState('');
|
|
const [hasError, setError] = useState(false);
|
|
|
|
useEffect(() => {
|
|
if (!mymap) {
|
|
return undefined;
|
|
}
|
|
|
|
const onMove = () => {
|
|
const {longitude, latitude} = mymap.getViewState();
|
|
setInputValue(`${longitude.toFixed(3)}, ${latitude.toFixed(3)}`);
|
|
setError(false);
|
|
};
|
|
mymap.on('move', onMove);
|
|
onMove();
|
|
|
|
return () => {
|
|
mymap.off('move', onMove);
|
|
};
|
|
}, [mymap]);
|
|
|
|
const onChange = useCallback(evt => {
|
|
setInputValue(evt.target.value);
|
|
}, []);
|
|
|
|
const onSubmit = useCallback(() => {
|
|
const [lng, lat] = inputValue.split(',').map(Number);
|
|
if (Math.abs(lng) <= 180 && Math.abs(lat) <= 85) {
|
|
mymap.easeTo({
|
|
center: [lng, lat],
|
|
duration: 1000
|
|
});
|
|
} else {
|
|
setError(true);
|
|
}
|
|
}, [mymap, inputValue]);
|
|
|
|
return (
|
|
<div style={{padding: 12, fontFamily: 'sans-serif'}}>
|
|
<span>MAP CENTER: </span>
|
|
<input
|
|
type="text"
|
|
value={inputValue}
|
|
onChange={onChange}
|
|
style={{color: hasError ? 'red' : 'black'}}
|
|
/>
|
|
<button onClick={onSubmit}>GO</button>
|
|
</div>
|
|
);
|
|
}
|