由于百度地图在国外的某些寻路的场景不太完善,所以试用了一下俄罗斯的开源地图。同google地图一样,规划路线需要申请apikey,但无需绑定信用卡,每天的免费调用次数也非常够用。
yandex maps开发文档
申请apikey
只需要创建账号,按指引申请就好了。
申请页面是俄文的,没关系,勾选下面这个选项然后点击下一步就好
JavaScript API и HTTP Геокодер
查看使用次数
https://developer.tech.yandex.ru/services/3
引入
由于yandex默认是[ 纬度,经度 ],所以在引入时修改了默认方式,设置成我们熟悉的经纬度
<script
src="https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=en_US&coordorder=longlat"
type="text/javascript"></script>
初始化
ymaps.ready(function () {
const yandexMap = new ymaps.Map(id, {
center: [24.9042208, 14.3782747], // 苏丹
zoom: 7,
controls: ['zoomControl', 'fullscreenControl'],
});
});
如果仅仅是想更改地图中心点
yandexMap.setCenter([ 3.610998, 51.4987962 ], 7) // 南非
声明GeoObjectCollection
GeoObjectCollection可增加多个,用来操作不同类型的元素
const pCollection = new ymaps.GeoObjectCollection();
yandexMap.geoObjects.add(pCollection); // 将集合添加到map
// pCollection.removeAll(); // 移除集合中所有的元素
根据经纬度获取城市名称
假定经纬度为coords
const myReverseGeocoder = ymaps.geocode(coords, { kind: 'locality' });
myReverseGeocoder.then(
function (res) {
console.log(res);
const obj = res.geoObjects.get(0);
const name = obj.properties.get('name'); // 地点名称
const address = obj.properties.get('text'); // 详细地址
},
function (err) {
// todo 提示获取失败
console.log('地点获取失败 === ', err);
}
);
显示气泡
pCollection.add(
new ymaps.Placemark([ 3.610998, 51.4987962 ], {
iconCaption: '这里是南非',
})
);
规划显示路线
如果自己添加路线,可显示多条不同出发地目的地的路线
const multiRoute = new ymaps.multiRouter.MultiRoute({
referencePoints: [start, end], // 出发地和目的地经纬度或地址名称
params: {
routingMode: 'auto',
},
});
pCollection.add(multiRoute);
在路线中获取后增加某些处理(不要擅自存储这些信息,这在免费的yandex中是不被允许的)
const multiRoute = new ymaps.multiRouter.MultiRoute({
referencePoints: [startAddress, endAddress],
params: {
routingMode: 'auto',
},
});
multiRoute.model.events.add('requestsuccess', function () {
try {
const activeRoute = multiRoute.getActiveRoute();
const distance = activeRoute.properties.get('distance').text; // 距离
const duration = activeRoute.properties.get('duration').text; // 时间
const boundedBy = activeRoute.properties.get('boundedBy');
// const activeRoutePaths = activeRoute.getPaths()
// console.log(
// 'activeRoutePaths: ',
// activeRoutePaths.properties.getAll()
// )
// activeRoutePaths.each(function (path) {
// console.log('path: ', path.properties)
// })
}
} catch (e) {
console.log(`${startAddress} To ${endAddress}的路线绘制失败 === `, e);
}
});