google maps middle of a polyline (centroid?)

fxck picture fxck · Oct 19, 2011 · Viewed 14.1k times · Source

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?

Answer

fxck picture fxck · Dec 19, 2011

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.