如何在Google Map上为多组起止坐标添加不同颜色标记点
解决方案:为起止坐标添加不同颜色标记点
没问题!要给你的起止坐标加上不同颜色的标记点来增强辨识度,只需要在你现有的循环逻辑里,额外创建Marker实例就行。咱们直接修改代码,给起点和终点分别设置不同的颜色:
修改后的完整代码
var geocoder; var map; function initialize() { var center = new google.maps.LatLng(51.97559, 4.12565); map = new google.maps.Map(document.getElementById('map'), { center: center, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP }); var bounds = new google.maps.LatLngBounds(); var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758']; var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758']; var paths = []; // 定义起止点的颜色,这里用Google Maps内置的图标颜色 const startMarkerColor = 'blue'; const endMarkerColor = 'green'; for (var i=0; i < end.length; i++){ var startCoords = start[i].split(","); var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]); var endCoords = end[i].split(","); var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]); paths.push([startPt, endPt]); bounds.extend(startPt); bounds.extend(endPt); // 创建起点标记 new google.maps.Marker({ position: startPt, map: map, title: `起点 ${i+1}`, icon: `http://maps.google.com/mapfiles/ms/icons/${startMarkerColor}-dot.png` }); // 创建终点标记 new google.maps.Marker({ position: endPt, map: map, title: `终点 ${i+1}`, icon: `http://maps.google.com/mapfiles/ms/icons/${endMarkerColor}-dot.png` }); } map.fitBounds(bounds); var polyline = new google.maps.Polygon({ paths: paths, strokeColor: 'red', strokeWeight: 2, strokeOpacity: 1 }); polyline.setMap(map); } google.maps.event.addDomListener(window, "load", initialize);
关键改动说明
- 在循环内部,处理完每一组
startPt和endPt后,分别创建了Marker实例 - 用Google Maps提供的内置彩色图标(
blue-dot.png和green-dot.png)来区分起止点,你也可以换成其他颜色,比如red、yellow、purple等 - 给标记添加了
title属性,鼠标悬停时会显示对应的起点/终点序号,进一步提升辨识度 - 直接把标记绑定到地图上(
map: map),不需要额外调用setMap(当然你也可以分开写)
如果需要更个性化的标记样式,比如自定义图标或者改变标记大小,你可以把icon属性换成一个对象,比如:
icon: { url: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', scaledSize: new google.maps.Size(20, 20) // 调整标记大小 }
这样修改后,你的地图上就会显示蓝色的起点标记和绿色的终点标记,和红色的连接线搭配,辨识度一下子就上来啦!
内容的提问来源于stack exchange,提问作者jovicbg
相关产品推荐
相关产品推荐

