谷歌地图API v3动态生成线路
Google Maps API v3 generating lines dynamically?
我正在制作一个谷歌地图原型,我想画一条线连接我地图上的每个标记。但是,目前我正在硬编码线的坐标与用于标记的坐标分开,并且想知道如何使其动态化,以便我只需要添加标记,线将从这些点自动生成。
我想动态生成的脚本部分被注释
这是我当前的代码:
<!DOCTYPE html>
<html>
<head>
<title>Travel Log</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
var locations = [
['Mankato, MN', 44.1834814, -93.9774519, 1],
['Duluth, MN', 46.7649885, -92.1112232, 2],
['Rochester, MN', 43.9959876, -92.4811724, 3],
['Fargo, ND', 46.8541979, -96.8285138, 4],
['Minneapolis, MN', 44.970697, -93.2614785, 5]
];
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(46.4418595,-93.3655146)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
/////////////////////////////////////////
//This is the part I want to be dynamic//
/////////////////////////////////////////
var lineCoordinates = [
new google.maps.LatLng(44.1834814, -93.9774519),
new google.maps.LatLng(46.7649885, -92.1112232),
new google.maps.LatLng(43.9959876, -92.4811724),
new google.maps.LatLng(46.8541979, -96.8285138),
new google.maps.LatLng(44.970697, -93.2614785)
];
var tripPath = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: '#000',
strokeOpacity: 1.0,
strokeWeight: 2
});
tripPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
JSFiddle
你可以很好地
使用 Array.prototype.map()
方法做到这一点;
var lineCoordinates = locations.map(function (val) {
return new google.maps.LatLng(val[1], val[2]);
});
http://jsfiddle.net/r3x4qcnk/1/
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 动态分配GA增强型电子商务跟踪器
- onkeyup无法动态创建多个文本区域
- 使用javascript将动态表从一个html页面打印到另一个html页
- 如何使Javascript动态html表及其上的事件
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 如何在Bootstrap Modal中为动态点击生成的变量设置jade属性
- 如何使用javascript从主svg对象动态创建svg视图框
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 通过在Dojo mobile ViewController.openExternalView中动态更改打开同一外部视图的
- 如何在Google柱状图中动态添加行/列
- 困在逻辑中试图定位动态的东西
- 在动态创建的元素上获取对特定选择器的引用
- 如何动态插入jquery代码
- 使用Google Visualization动态调用构造函数
- 使用jQuery动态添加表并在其中动态添加行
- d3基于用户选择动态更新节点
- 使用JQuery的动态上下文菜单
- 谷歌地图API v3动态生成线路