在项目中,使用百度地图时,发现通过城市名获取经纬度不准确,故替换为高德地图。

代码如下:
var points = []
var adds = ['江苏省无锡市惠山区','江苏省常州市金坛市','江苏省泰州市姜堰县']
var startIcon = new AMap.Icon({
// 图标尺寸
size: new AMap.Size(22, 28),
image:'http://new.tzwlpzw.com/homeStatic/images/dt_start.png',
// 图标所用图片大小
imageSize: new AMap.Size(22, 28),
})
var throughIcon = new AMap.Icon({
// 图标尺寸
size: new AMap.Size(22, 28),
image:'http://new.tzwlpzw.com/homeStatic/images/dt_through.png',
// 图标所用图片大小
imageSize: new AMap.Size(22, 28),
})
var endIcon = new AMap.Icon({
// 图标尺寸
size: new AMap.Size(22, 28),
image:'http://new.tzwlpzw.com/homeStatic/images/dt_end.png',
// 图标所用图片大小
imageSize: new AMap.Size(22, 28),
})
//在轨迹点上创建图标
function addMarker(points){ // 创建图标对象
for(var i = 0,pointsLen = points.length;i <pointsLen;i++){
if ( i < 1 ) {
var marker = new AMap.Marker({
position: new AMap.LngLat(points[i].location.lng,points[i].location.lat),
icon: startIcon,
offset: new AMap.Pixel(-11, -28)
});
marker.setMap(map);
marker.setLabel({
offset: new AMap.Pixel(-10, -5), //设置文本标注偏移量
content: "<div class='info'>"+points[i].formattedAddress+"</div>", //设置文本标注内容
direction: 'right' //设置文本标注方位
});
} else if ( i === points.length - 1 ) {
var marker = new AMap.Marker({
position: new AMap.LngLat(points[i].location.lng,points[i].location.lat),
icon: endIcon,
offset: new AMap.Pixel(-11, -28)
});
marker.setMap(map);
marker.setLabel({
offset: new AMap.Pixel(-10, -5), //设置文本标注偏移量
content: "<div class='info'>"+points[i].formattedAddress+"</div>", //设置文本标注内容
direction: 'right' //设置文本标注方位
});
} else {
var marker = new AMap.Marker({
position: new AMap.LngLat(points[i].location.lng,points[i].location.lat),
icon: throughIcon,
offset: new AMap.Pixel(-11, -28)
});
marker.setMap(map);
marker.setLabel({
offset: new AMap.Pixel(-10, -5), //设置文本标注偏移量
content: "<div class='info'>"+points[i].formattedAddress+"</div>", //设置文本标注内容
direction: 'right' //设置文本标注方位
});
}
}
}
// 批量地址解析
function AGEO() {
if (index < adds.length) {
var add = adds[index];
geoCode(add);
index++;
} else {
console.log(points)
addMarker(points); // 绘制图标
createPolyline (points); // 绘制折线
var newCenter = map.setFitView();
}
}
function geoCode(add) {
if(index < adds.length){
setTimeout(window.bdGEO,400);
}
geocoder.getLocation(add, function(status, result) {
if (status === 'complete'&&result.geocodes.length) {
points.push(result.geocodes[0])
}else{
log.error('根据地址查询位置失败');
}
});
}
function createPolyline(points) {
var polylinePath = []
for (var i = 0,pointsLen = points.length;i <pointsLen;i++) {
polylinePath[i] = new AMap.LngLat(points[i].location.lng,points[i].location.lat);
}
console.log(polylinePath )
// 创建线覆盖物
var polyline = new AMap.Polyline({
path: polylinePath
});
map.add([polyline]);
}
var map = new AMap.Map("container", {
resizeEnable: true
});
var geocoder = new AMap.Geocoder({
city: "全国",
});
var index = 0;
AGEO()