Is there anyway to convert the bounds and/or center position to string and send it to the server side by json and store it?
I am asking because when I try to convert these stuff into string; I am getting conversion error from the api?
Is there anyway to convert the bounds and/or center position to string and send it to the server side by json and store it?
I am asking because when I try to convert these stuff into string; I am getting conversion error from the api?
Use serialize
function, for retrieving map bounds and center data, then store it in DB.
function serialize(map){
var json = '{"bounds":'+map.getBounds().toString() +
',"center":'+map.getCenter().toString()+"}";
//'toString' returns values in '()', we need to replace them by '[]'
json = json.replace(/\(/g,"[").replace(/\)/g,"]");
return json;
}
Use deserialize
function, for updating map's state,by stored data:
function deserialize(map, json, useCenter ){
json = JSON.parse(json);
if( useCenter ){
map.setCenter( new google.maps.LatLng(json.center[0],json.center[1]) );
}else{
map.fitBounds( new google.maps.LatLngBounds(
new google.maps.LatLng(json.bounds[0][0],json.bounds[0][1]),
new google.maps.LatLng(json.bounds[1][0],json.bounds[1][1])
) );
}
}
IMPORTANT: map.fitBounds
won't fit to exact bounds of its argument. See this link.