📅  最后修改于: 2023-12-03 15:16:16.377000             🧑  作者: Mango
我们通过Javascript可以实现将用户从当前网页导航到谷歌地图并且规划路线。
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
其中,YOUR_API_KEY为你在Google Cloud Console获取的API Key。
<div id="map"></div>
function initMap() {
// 创建地图
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.774, lng: -122.419},
zoom: 13
});
// 创建DirectionService对象
var directionsService = new google.maps.DirectionsService;
// 创建Display对象
var directionsDisplay = new google.maps.DirectionsRenderer;
// 将Display对象链接到地图上
directionsDisplay.setMap(map);
// 规划路线
directionsService.route({
origin: 'San Francisco',
destination: 'Mountain View',
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
// 在地图上显示规划的路线
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
document.getElementById('button').addEventListener('click', function() {
// 构建URL
var url = 'https://www.google.com/maps/dir/?api=1&destination=Mountain+View&origin=San+Francisco&travelmode=driving';
// 跳转
window.location.href = url;
});
通过Javascript,我们可以轻松地在网页上实现跳转到谷歌地图,并且展示规划好的路线。这给用户提供了更好的体验,并且可以提高用户的使用效率。