Andres SK
Andres SK

Reputation: 10974

Marker in Polygon path

I managed to center a marker inside a polygon path by extending the getBounds method:

//polyline
google.maps.Polyline.prototype.getBounds = function() {
    var bounds = new google.maps.LatLngBounds();
    this.getPath().forEach(function(e) {
        bounds.extend(e);
    });
    return bounds;
};

All I have to do is this:

var marker = new google.maps.Marker({
    map: map,
    position: flight_path.getBounds().getCenter()
});

Now I want the marker to be at 10%, 25% or 95% of the path.
How can I achieve that?

Upvotes: 1

Views: 966

Answers (1)

duncan
duncan

Reputation: 31912

You can use the Geometry library to work this out. Add libraries=geometry to the Google Maps JS URL.

Then use the interpolate function to work out what percentage along your polyline you place your marker.

var inBetween = google.maps.geometry.spherical.interpolate(startLatlng, endLatLng, 0.5);  // 50%

This is simple on one polyline, but if you have multiple lines forming one path, it might be a bit trickier! You could then maybe use computeLength to calculate the overall path length, do the maths yourself for where 95% is, and then I'm not sure...

Upvotes: 2

Related Questions