我想创建一个从用户位置到特定目的地的路线的地图。我的地图和方向运行正常,但是当我请求并显示带有路线的地图时,中心已移动。我希望地图的中心仍然相同。我希望有人能帮助我。
这是我的地图代码,没有我的Api键和地图样式。
<script>
var start_location = {
lat: 50.697686,
lng: 14.812066
};
var center_location = {
lat: 50.699328,
lng: 14.820216
};
var marker_location = {
lat: 50.698328,
lng: 14.810216
};
function initMap() {
var map_options = {
center: center_location,
zoom: 15
}
var marker = new google.maps.Marker({
position: marker_location
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), map_options);
marker.setMap(map);
directionsDisplay.setMap(map);
document.getElementById('btnCesta').addEventListener('click', Getlocation);
function Getlocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
start_location = {
lat: pos.lat,
lng: pos.lng
};
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
} else {}
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: start_location,
destination: '50.697373, 14.811364',
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>