Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google maps middle of a polyline (centroid?)

I have a list of polylines, just like google maps does when I click on the polyline I want an infowindow to show up just where I clicked, and it works just fine with this function

function mapsInfoWindow(polyline, content) {
    google.maps.event.addListener(polyline, 'click', function(event) {            
        infowindow.content = content;
        infowindow.position = event.latLng;
        infowindow.open(map);
    });
}

the problem comes when I click on the list(using the same function for that), event obviously doesn't have the latLng, but I'd like infowindow to show up in the middle of the polyline anyway, just like it does when you click on the list in the google maps link I mentioned before.

Tried LatLngBounds(); but that gives the actuall center of the area the polylines create, not the middle I need.

Any idea how to do it?

like image 864
fxck Avatar asked Dec 06 '22 18:12

fxck


2 Answers

So this is the(bit hacky) solution.

Use http://www.geocodezip.com/scripts/v3_epoly.js library, then count the total length of you polyline(various ways), divide it in half and call epoly's .GetPointsAtDistance() function upon it.

This should return LatLng point, but it acts a bit weird sometimes, returning two points or even turning that point somehow "broken". So the most secure thing you can do is probably this:

var pointInHalf = polyline.GetPointsAtDistance(polylineLength);
var pointCoordinate = new google.maps.LatLng(pointInHalf[0].lat(), pointInHalf[0].lng());

Well, better than nothing.

like image 137
fxck Avatar answered Dec 10 '22 12:12

fxck


From http://www.geocodezip.com/v3_polyline_example_geodesic_proj.html

Without extensions and assuming the polyline is a straight line.

It is possible to convert the lat/lng coordinates to point plane (x,y) postions and calculate the average between the two. This will give you a central pixel position. You can then convert this position back to a latlng for map plotting.

var startLatLng = startMarker.getPosition(); 
var endLatLng = endMarker.getPosition(); 
var startPoint = projection.fromLatLngToPoint(startLatLng); 
var endPoint = projection.fromLatLngToPoint(endLatLng); 
// Average 
var midPoint = new google.maps.Point( 
    (startPoint.x + endPoint.x) / 2, 
    (startPoint.y + endPoint.y) / 2); 
// Unproject 
var midLatLng = projection.fromPointToLatLng(midPoint); 
var midMarker = createMarker(midLatLng, "text");

More information on changing the projection http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection

like image 26
Shane Best Avatar answered Dec 10 '22 12:12

Shane Best