【发布时间】:2017-02-06 01:38:04
【问题描述】:
我使用 Google Maps API as seen in this example 在两点之间绘制了一条折线。现在我想生成沿同一条线的其他点。有这样的功能吗?
我不想在这条线上添加一些随机点;我希望这些点位于两个端点之间生成的曲线上。
【问题讨论】:
标签: google-maps google-api google-api-js-client
我使用 Google Maps API as seen in this example 在两点之间绘制了一条折线。现在我想生成沿同一条线的其他点。有这样的功能吗?
我不想在这条线上添加一些随机点;我希望这些点位于两个端点之间生成的曲线上。
【问题讨论】:
标签: google-maps google-api google-api-js-client
您可以使用interpolate function of the spherical geometry library来计算直线任意线段上的点的位置:
var marker2 = new google.maps.Marker({
map: map,
position: google.maps.geometry.spherical.interpolate(
new google.maps.LatLng(flightPlanCoordinates[1].lat,flightPlanCoordinates[1].lng),
new google.maps.LatLng(flightPlanCoordinates[2].lat,flightPlanCoordinates[2].lng),
0.6)
});
(请注意,interpolate 函数只接受 google.maps.LatLng 对象作为参数,而不接受 google.maps.LatLngLiterals,至少目前是这样)
代码 sn-p:
// This example creates a 2-pixel-wide red polyline showing the path of William
// Kingsford Smith's first trans-Pacific flight between Oakland, CA, and
// Brisbane, Australia.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [{
lat: 37.772,
lng: -122.214
}, {
lat: 21.291,
lng: -157.821
}, {
lat: -18.142,
lng: 178.431
}, {
lat: -27.467,
lng: 153.027
}];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
var marker = new google.maps.Marker({
map: map,
position: google.maps.geometry.spherical.interpolate(new google.maps.LatLng(flightPlanCoordinates[0].lat, flightPlanCoordinates[0].lng), new google.maps.LatLng(flightPlanCoordinates[1].lat, flightPlanCoordinates[1].lng), 0.75)
});
var marker2 = new google.maps.Marker({
map: map,
position: google.maps.geometry.spherical.interpolate(new google.maps.LatLng(flightPlanCoordinates[1].lat, flightPlanCoordinates[1].lng), new google.maps.LatLng(flightPlanCoordinates[2].lat, flightPlanCoordinates[2].lng), 0.6)
});
var marker3 = new google.maps.Marker({
map: map,
position: google.maps.geometry.spherical.interpolate(new google.maps.LatLng(flightPlanCoordinates[2].lat, flightPlanCoordinates[2].lng), new google.maps.LatLng(flightPlanCoordinates[3].lat, flightPlanCoordinates[3].lng), 0.8)
});
flightPath.setMap(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry&callback=initMap">
</script>
【讨论】: