Closed JakhongirUrmonov closed 4 years ago
I used Geocode library it works with the help of google map api, is there any ways to get same result without Geocode library?
@CooperSky like so:
import React from "react";
import { YMaps, Map } from "react-yandex-maps";
const mapState = {
center: [55.753994, 37.622093],
zoom: 9
};
export default function App() {
const ymaps = React.useRef(null);
const placemarkRef = React.useRef(null);
const mapRef = React.useRef(null);
const [address, setAddress] = React.useState("");
const createPlacemark = (coords) => {
return new ymaps.current.Placemark(
coords,
{
iconCaption: "loading.."
},
{
preset: "islands#violetDotIconWithCaption",
draggable: true
}
);
};
const getAddress = (coords) => {
placemarkRef.current.properties.set("iconCaption", "loading..");
ymaps.current.geocode(coords).then((res) => {
const firstGeoObject = res.geoObjects.get(0);
const newAddress = [
firstGeoObject.getLocalities().length
? firstGeoObject.getLocalities()
: firstGeoObject.getAdministrativeAreas(),
firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
]
.filter(Boolean)
.join(", ");
setAddress(newAddress);
placemarkRef.current.properties.set({
iconCaption: newAddress,
balloonContent: firstGeoObject.getAddressLine()
});
});
};
const onMapClick = (e) => {
const coords = e.get("coords");
if (placemarkRef.current) {
placemarkRef.current.geometry.setCoordinates(coords);
} else {
placemarkRef.current = createPlacemark(coords);
mapRef.current.geoObjects.add(placemarkRef.current);
placemarkRef.current.events.add("dragend", function () {
getAddress(placemarkRef.current.geometry.getCoordinates());
});
}
getAddress(coords);
};
return (
<div className="App">
<YMaps query={{ apikey: "your api key" }}>
<Map
modules={["Placemark", "geocode", "geoObject.addon.balloon"]}
instanceRef={mapRef}
onLoad={(ympasInstance) => (ymaps.current = ympasInstance)}
onClick={onMapClick}
state={mapState}
/>
{address && (
<div>
<p>{address}</p>
</div>
)}
</YMaps>
</div>
);
}
Thanks a lot, I did something different
export const App = (props) => {
const [ addressName, setAddressName ] = useState(false);
const getCoords = e => {
window.ymaps.geocode(e.get('coords')).then(res => {
let firstGeoObject = res.geoObjects.get(0);
setAddressName(firstGeoObject.getAddressLine())
})
};
const mapState = {
center: [41.3110, 69.2405],
zoom: 13
};
return (
<div>
<YMaps query={{
apikey: 'API_KEY,
ns: "ymaps",
}}>
<Map
state = {mapState}
modules= {["geolocation", "geocode"]}
onClick={e => getCoords(e)}
>
<Placemark
geometry={{
type: 'Point',
coordinates: coords,
} }
properties={{
iconContent: addressName,
}}
options={{
preset: 'islands#blackStretchyIcon',
}}
/>
</Map>
</YMaps>
<div>
</div>
</div>
)
};
which code is better and why? Please, could you explain to me?
@CooperSky that's totally fine to use your code. I'm just not sure where you update your Placemark coordinates. Personally I don't like to use window to call ymaps methods.
I got you, thanks one more time.