Answer the question
In order to leave comments, you need to log in
Why doesn't Google Maps build a route between two points?
I just started using the Google Maps API and I want to make 2 textboxes where I specify the start and end points. I can't get it right in JS .
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Maps</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="floating-panel">
<label for="sityname-start">Название начального города: </label>
<input type="text" name="sityname-start" id="sityname-start" />
<label for="sityname-end">Название конечного города: </label>
<input type="text" name="sityname-end" id="sityname-end" />
<input id="button" type="button" value="Рассчитать" />
</div>
<section id="map"></section>
<script src="js/main.js" defer></script>
<script src="https://maps.googleapis.com/maps/api/js?key={MY_API_KEY}&callback=initMap" defer></script>
</body>
</html>
#map {
height: 100vh;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
input[type="button"] {
cursor: pointer;
}
function initMap() {
var coords = {lat: 46.9704762, lng: 31.9852023},
container = document.getElementById('map'),
content = container.innerHTML,
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer,
map = new google.maps.Map(container, {
center: coords,
zoom: 14
});
infowindow = new google.maps.InfoWindow({
content: content
});
// Apply new JSON when the user selects a different style.
styleSelector.addEventListener('change', function() {
map.setOptions({styles: styles[styleSelector.value]});
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('button').addEventListener('click', onChangeHandler);
// document.getElementById('sityname-end').addEventListener('click', onChangeHandler);
directionsDisplay.setMap(map);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('sityname-start').value,
destination: document.getElementById('sityname-end').value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question