google maps middle of a polyline (centroid?)

拜拜、爱过 提交于 2019-12-01 09:24:52

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.

Shane Best

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

So firstly you need to use the geometry library which calculates distances. Add libraries=geometry to your JS call, e.g.

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>

Assuming you know the start point and end point for your polyline, you should be able to do this:

var inBetween = google.maps.geometry.spherical.interpolate(startLatlng, endLatlng, 0.5);  
infowindow.position = inBetween;

I guess if you don't already know the start and end points, you could work it out from polyline.getPath().

Jefferson Maretti

to get the coordinates of your polyline you should do:

var widePath = new google.maps.Polyline({
path: waypointsCoordinates,
strokeColor: '#3366FF',
strokeOpacity: 0.0,
editable: true,
draggable: true,                       
strokeWeight: 3
});

and do:

var latLng [];
latLng = widePath.getPath().getArray();

Might be a bit old as well, but why not add the infobox on the click?

infowindow.setPosition(event.latLng);
infowindow.open(this.getMap());

If it's a click that is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!