How to get map center lat long in arcgis javascript api?
I looked the api reference of 'Map' object, only see map.getZoom()
There is NO such method map.getCenter()
On google map api v3, map is the google map object, this is how you get map center lat, long, and zoom level.
center_latLng = map.getCenter();
center_lat = center_latLng.lat();
center_long = center_latLng.lng();
center_zoom = map.getZoom();
However, arcgis api is little different, map is arcgis map object, you will use extend property.
center_latLng = map.extent.getCenter();
center_lat = center_latLng.getLatitude();
center_long = center_latLng.getLongitude();
center_zoom = map.getZoom();
Usually, when you get current map lat, long, zoom level, you want to update the current web page query URL, which has old info before map extend change.
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("center_lat", center_lat);
searchParams.set("center_long", center_long);
searchParams.set("center_zoom", center_zoom);
// this cause reload https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter
//window.location.search = searchParams.toString();
// instead avoid reload
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}// if
So the whole function is:
function update_center_latLngZoom(){
center_latLng = map.extent.getCenter();
center_lat = center_latLng.getLatitude();
center_long = center_latLng.getLongitude();
center_zoom = map.getZoom();
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("center_lat", center_lat);
searchParams.set("center_long", center_long);
searchParams.set("center_zoom", center_zoom);
// this cause reload https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter
//window.location.search = searchParams.toString();
// instead avoid reload
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}// if
}// function
This function should be trigged by map move or zoom or extend change. You need to attach this function to map extend change event.
1) google map, attach to map idle event
map.addListener('idle', function() {
update_center_latLngZoom();
});
2)arcgis map api, attach to map extent-change event
map.on("extent-change", function(){
// url search parameter update
update_center_latLngZoom()
});