Google Maps API: Calculate Center/Zoom of Polyline - google-maps

I have an overlay that is dynamically generated from user data, so I need to know how to find the center of that overlay.
Currently, I am just using the first coordinates from the overlay, but that really does not represent the center of the overlay. Therefore when I load the map, it is not centered on the overlay.
Does anyone have a good method for centering the map on the overlay, by calculating the center, not hard coding it?
var latlng = new google.maps.LatLng(38.269239, -122.276010);
var myOptions = {
zoom: 15,//Calculate this somehow?
center: latlng,// Calculate value from array of coordinates?
mapTypeId: google.maps.MapTypeId.HYBRID
};

If you have a list of coordinates, you can loop over them and add them to a LatLngBounds object. Here is a example for the V3 API, but the concept in V2 is similar:
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coordinates.length; i++) {
bounds.extend(coordinates[i]);
}
After that, you can get the center with:
bounds.getCenter();
Or alternatively, you can call map.fitBounds() directly, which will center the map around the center of the bounds and adjust the zoom, so that the whole bounds will fit exactly into the view port.
map.fitBounds(bounds);

Based on #tux21b,
var bounds = new google.maps.LatLngBounds();
polyline.getPath().forEach(function(e){//can't do polyline.getPath()[i] because it's a MVCArray
bounds.extend(e);
})
_map.fitBounds(bounds);

Related

Make polyline to show on google map horizontally and zoom it to center coordinate

I am using Google Maps API JavaScript. My use case is I need to plot coordinates (lat, lng) on maps (create markers) and join them through polyline. The co-ordinates will be very close to each other so when I try to plot them, they get hidden behind the first marker. So I find out the center and try to zoom so that all markers will be visible on the map.
I used bounds to find the center but I am not able to zoom it to center co-ordinate. I used map.fitBounds(latlng); It fits the coordinate on the screen.
But what I want to achieve is to make polyline (connecting all co-ordinate) always horizontal and zoom it to center co-ordinate.
enter code herevar bounds = new google.maps.LatLngBounds();
for (i = 0; i < temp.length; i++) {
bounds.extend(temp[i]);
}
var latlng = bounds.getCenter();
map.setCenter(latlng);
As the coordinate will always be different, The polyline will be in any direction, but I always want to show it horizontally on the map.
what I get :
enter image description here
what i want to acheive:
enter image description here
Any suggestion will be appreciated.
Thanks in Advance.
I achieve something like this by using the following:
Use computeHeading() function of Geometry library to get the angle from your first to your last coordinate on the line. Make sure to add &libraries=geometry to your Maps JS script tag.
Once you get the heading, you can use the map.setHeading() function to change the angle of your view and after some testings,I can see that you can achieve the horizontal view by subtracting it to 90 degrees.
Here's the sample code and code snippet below:
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 40.756795,
lng: -73.954298
},
zoom: 16,
tilt: 47.5,
mapId: "90f87356969d889c",
});
//array of your points
const markerCoordinates = [
{ lat: 40.758481, lng: -73.958269 },
{ lat:40.754649, lng: -73.949563 },
];
//creating marker from your points
for (let i = 0; i < markerCoordinates.length; i++) {
const marker = markerCoordinates[i];
new google.maps.Marker({
position:marker,
map,
});
}
//creating polyline from your points
const createdPolyline = new google.maps.Polyline({
path: markerCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
createdPolyline.setMap(map);
//get the heading(angle) of the first coordinate from the last coordinate
const heading = google.maps.geometry.spherical.computeHeading(
markerCoordinates[0],
markerCoordinates[1]
)
//once you get the heading subtract it by 90 to get a horizontal view
map.setHeading(heading-90)
}

Set the marker position in Google Map

I want to know how can I change the position of the marker in the Google Map.
Currently I'm using:
var newlatlong = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
map.setCenter(newlatlong);
marker.setPosition(newlatlong);
map.setZoom(10);
Can I hand code the position of the marker in the map other than the center position?
I mean map.setCenter(newlatlong);, Instead of setCenter Is there any other position available? or can I hand code the position in the map where the marker should appear?
Not sure why you are running the code twice...
But yes, you can pass latitude/longitude values directly to the setCenter method
map.setCenter({lat: -34, lng: 151});
Documentation: https://developers.google.com/maps/documentation/javascript/reference#Map
update after comments
If you want to move the map center so that the marker is specific position (in pixels), you can center on the marker and then use the .panBy method to move the map a fixed amount of pixels.
To create a marker:
var marker = new google.maps.Marker({
map : map,
position : newlatlong
})
to update the position of this marker:
marker.setPosition(newlatlong);
to put the center at the east of marker, for example:
map.setCenter(new LatLng(newlatlong.lat,newlatlong.lng + 1.0))
You can set the center of the map and the marker separately using different longitude and latitudes:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.512318, -72.979349);
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(41.513001, -72.983845)
});
};
This makes the marker slightly off center to the left. I used this in a current project of mine.

Google maps Zoom to Marker Position

Not sure if this is possible but I have set my map up with custom styles and marker and I want to ensure the map shows at this level but with London in view. To do so I centred the map at a different location to my marker. I would like the map to zoom to my location if possible instead of the centre.
var myLatlng = new google.maps.LatLng('51.4525368','0.2481994');
var mapOptions = {
center: new google.maps.LatLng('51.4600368','0.0781994'),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 11,
mapTypeControl: false,
scrollwheel:false
};
Also if anybody can tell me why my info window is displaying all funky I would appreciate too.
It has been tough to understand your question but if I got you right, you are trying to fit both center of London and your location on the map without setting a center on some position on the map. If that's correct, then you need google.maps.LatLngBounds() to get it done.
var bounds= new google.maps.LatLngBounds();
var London= new google.maps.LatLng(//London values);
var myLatLng = new google.maps.LatLng(//your values);
bounds.extend(London);
bounds.extend(myLatLng);
map.fitBounds(bounds);
Check if this serves your purpose.

refresh the circle on google map

I'm implementing an application in which I have to show google map with circle at the center of the map. I'm able draw a circle on map but after few seconds I've to update the circle's radius. I want to use same instance of map rather than creating new one.
When i create the new circle its overlapping on older circle. I want to remove previously added circle and show new one.
While checking the api I got this method from Circle class which will hide the circle.
myCity.setOptions({visible:false});
but the problem is I don't have access to older circle instance.
Is there any way which will allow me to get maps markers and infoboxes assigned to that map and remove them?
Below is method which will get called interval of few seconds
function mapByCoordinates()
{
var lat=document.getElementById("latValue").value;
var lng=document.getElementById("lngValue").value;
var accuracy = document.getElementById("zoomValue").value;
var zoomVal=getZoomBasedOnAccuracy(accuracy);
var zm = parseInt(zoomVal);
var tempRadius = getRadiusBasedOnAccuracy(accuracy);
var amstr = new google.maps.LatLng(lat,lng);
var mapProp = {
center:amstr,
zoom:zm,
mapTypeId:google.maps.MapTypeId.HYBRID
};
map.setOptions(mapProp);
myCity.setOptions({visible:false});
infobox.close();
myCity = new google.maps.Circle({
center:amstr,
radius:tempRadius
});
marker=new google.maps.Marker({
position:amstr,
});
myCity.setMap(map);
myCity1.setMap(map1);
infobox = new google.maps.InfoWindow({
content:"Welcome to google map",
disableAutoPan:true
});
infobox.open(map,marker);
map.panTo(amstr);
map.setZoom(19);
}
Thanks
We can make the already drawn circle invisible on google maps by using following method
circle.setOptions({visible:false});
and can null the instance of that map.
Try circle.setRadius(radiusvalue)

Google Maps javascript API- Map object recenters after applying KML layer. How do I prevent this?

Google Maps javascript API question - Map object recenters after applying KML layer. How do I prevent this?
I created a simple page with a map. When I apply a simple polygon KML, it recenters and zooms the map. Any ideas?
var myOptions = {
center: new google.maps.LatLng(27, -97),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var buildings = new google.maps.KmlLayer('https://mysite/site/buildings.xml');
buildings.setMap(map);
//i tried this to recenter and zoom, but no dice.
var posn = new google.maps.LatLng(27, -97);
map.setCenter(posn);
map.setZoom(17);
Sounds like you need the preserveViewport option. From the documentation:
By default, the input map is centered and zoomed to the bounding box of the contents of the layer. If this option is set to true, the viewport is left unchanged, unless the map's center and zoom were never set.
Pass it a KMLLayerOptions object through the constructor:
var buildings = new google.maps.KmlLayer('https://mysite/site/buildings.xml',{preserveViewport:true});