Here is a small application i'm writing to check a taxi fare in my country. everything is working well, including autocomplete. but if i type a building/mall name, the route is not showing. but if i type a road name, then the route is showing.
road name example in my city is : "jalan salemba raya" and "jalan medan merdeka timur"
mall name example : "Amaris Hotel Mangga Dua Square"
where is the problem ?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<title>Distance Calculator</title>
<script type="text/javascript" src="http://maps.google.co.id/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var city = new google.maps.LatLng(-6.17503,106.826935);
var myOptions = {
zoom:17,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: city
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('start'));
var autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('end'));
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var distanceDisplay = document.getElementById("distance");
var timeDisplay = document.getElementById("time");
var tarifDisplay = document.getElementById("tarif");
var request = {
origin:start,
destination:end,
avoidTolls:true,
provideRouteAlternatives:true,
region:'co.id',
avoidHighways:true,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
jarak = Math.round((response.routes[0].legs[0].distance.value / 1000) * 100) /100;
distanceDisplay.value = jarak + ' km';
timeDisplay.value = Math.round((response.routes[0].legs[0].duration.value+1020) /60, 2) + ' menit';
tarifDisplay.value = 'Rp '+ Math.floor( (jarak*3240) + 3500) + ',-';
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" placeholder="masukkan alamat"/>
<label for="end">End: </label>
<input type="text" name="end" id="end" placeholder="masukkan alamat"/>
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Jarak: </label>
<input type="text" name="distance" id="distance" readonly />
</p>
<p>
<label for="time">Estimasi waktu: </label>
<input type="text" name="time" id="time" readonly />
</p>
<p>
<label for="tarif">Tarif: </label>
<input type="text" name="tarif" id="tarif" readonly />
</p>
</div>
<div id="map_canvas" style="height:100%;width:100%"></div>
</body>
</html>
Since all you need is the distance and the route, you should use the coordinates provided by the autocomplete service. See the documentation for how to access the coordinates that result when the user selects a suggestion:
var startCoord, endCoord;
google.maps.event.addListener(autocomplete1, 'place_changed', function() {
var place = autocomplete1.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
startCoord = place.geometry.location
});
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
var place = autocomplete2.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
endCoord = place.geometry.location
});
Then use startCoord and endCoord in your directions request.
proof of concept fiddle
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var startCoord, endCoord;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var city = new google.maps.LatLng(-6.17503, 106.826935);
var myOptions = {
zoom: 17,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: city
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('start'));
var autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('end'));
google.maps.event.addListener(autocomplete1, 'place_changed', function() {
var place = autocomplete1.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
startCoord = place.geometry.location
});
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
var place = autocomplete2.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
endCoord = place.geometry.location
});
}
function calcRoute() {
var start, end;
if (!startCoord) {
start = document.getElementById("start").value;
} else {
start = startCoord;
}
if (!endCoord) {
end = document.getElementById("end").value;
} else {
end = endCoord;
}
var distanceDisplay = document.getElementById("distance");
var timeDisplay = document.getElementById("time");
var tarifDisplay = document.getElementById("tarif");
var request = {
origin: start,
destination: end,
avoidTolls: true,
provideRouteAlternatives: true,
region: 'co.id',
avoidHighways: true,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
jarak = Math.round((response.routes[0].legs[0].distance.value / 1000) * 100) / 100;
distanceDisplay.value = jarak + ' km';
timeDisplay.value = Math.round((response.routes[0].legs[0].duration.value + 1020) / 60, 2) + ' menit';
tarifDisplay.value = 'Rp ' + Math.floor((jarak * 3240) + 3500) + ',-';
} else {
alert("directions request failed, status=" + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div>
<p>
<label for="start">Start:</label>
<input type="text" name="start" id="start" placeholder="masukkan alamat" value='Museum Taman Prasasti, South Petojo, Special Capital Region of Jakarta, Indonesia' />
<label for="end">End:</label>
<input type="text" name="end" id="end" placeholder="masukkan alamat" value='Mangga Dua Square' />
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Jarak:</label>
<input type="text" name="distance" id="distance" readonly />
</p>
<p>
<label for="time">Estimasi waktu:</label>
<input type="text" name="time" id="time" readonly />
</p>
<p>
<label for="tarif">Tarif:</label>
<input type="text" name="tarif" id="tarif" readonly />
</p>
</div>
<div id="map_canvas"></div>
Related
I basically want to remove KM next to distance number because I want to calculate fare price and I can't make any calculations. I hope the given example below its understandable and please find the snippet code for HTML and javascript.
Example
Usually, it writes like this: 5 km
and I want it to be like this: 5
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// initialise the location of the map on Chichester in England (ref lat and lng)
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: { lat: 50.834697, lng: -0.773792 },
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('travelfrom'));
new google.maps.places.SearchBox(document.getElementById('travelto'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.value;
var dvDistance = document.getElementById("dvDistance");
var price = document.getElementById("price");
duration = parseFloat(duration / 60).toFixed(2);
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Time:" + duration + " min";
price.innerHTML = distance * 2.00;
} else {
alert("Unable to find the distance via road.");
}
});
}
<div class="row">
<div class="col-md-12">
<div>
<div>
Travel From : <input id="travelfrom" type="text" name="name" value="Chichester, UK" />
To : <input id="travelto" type="text" name="name" value="Goodwood aerodrone, UK" />
<input type="button" value="Get Route" onclick="GetRoute()" />
</div>
<br />
<div>
<div id="dvDistance">
</div>
<br />
<div id="price">
</div>
<br />
<br />
</div>
</div>
<div id="dvMap" style="min-height:500px"></div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
The text property of distance is a string which can contain a units specifier.
If you want a number, use the value property of distance which is a number and is always in meters.
var distance = response.rows[0].elements[0].distance.value/1000;
code snippet:
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// initialise the location of the map on Chichester in England (ref lat and lng)
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: {
lat: 50.834697,
lng: -0.773792
},
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addDomListener(window, 'load', function() {
new google.maps.places.SearchBox(document.getElementById('travelfrom'));
new google.maps.places.SearchBox(document.getElementById('travelto'));
directionsDisplay = new google.maps.DirectionsRenderer({
'draggable': true
});
});
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.value / 1000;
var duration = response.rows[0].elements[0].duration.value;
var dvDistance = document.getElementById("dvDistance");
var price = document.getElementById("price");
duration = parseFloat(duration / 60).toFixed(2);
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Time:" + duration + " min";
price.innerHTML = distance * 2.00;
} else {
alert("Unable to find the distance via road.");
}
});
}
html,
body {
height: 100%;
width: 100%;
}
<div class="row" style="height:100%;">
<div class="col-md-12" style="height:100%;">
<div style="height: 130px;">
<div>
Travel From : <input id="travelfrom" type="text" name="name" value="Chichester, UK" /> To : <input id="travelto" type="text" name="name" value="Goodwood aerodrone, UK" />
<input type="button" value="Get Route" onclick="GetRoute()" />
</div>
<br />
<div>
<div id="dvDistance">
</div>
<br />
<div id="price">
</div>
<br />
<br />
</div>
</div>
<div id="dvMap" style="height:65%;"></div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
How about just removing the "KM" form the string:
var distance = response.rows[0].elements[0].distance.text.toLowerCase().replace(" km", "");
If you want to make calculations with the distance, you should also change the variable's type to Number.
var distance = parseFloat(
response.rows[0].elements[0].distance.text.toLowerCase().replace(" km", "")
);
I have to create google maps direction service between 2 points / markers on map click event
I have prepared fiddle to illustrate how when you click on the map for a second time, a third marker is being printed on the map. Whatever I tried I could not succeed to remove the third marker.
The first marker has label A, second B, but the third is just being printed..
I will appreciate your time and help in solving this issue.
here is the fiddle
code snippet
var map;
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService.route({
origin: {
query: document.getElementById('departure_address').value
},
destination: {
query: document.getElementById('arrival_address').value
},
travelMode: 'DRIVING'
},
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
function initMap_mobile() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('mobilemap'), {
mapTypeControl: false,
center: {
lat: 42.700000762939,
lng: 23.333299636841
},
zoom: 13
});
directionsRenderer.setMap(map);
var marker;
var infowindow;
google.maps.event.addListener(map, 'click', function(event) {
//alert(marker.length);
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
//alert(event.latLng.lat() +"-"+ event.latLng.lng());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
}, function(results, status) {
//alert(results[0].formatted_address); //Final address from lat and lng
//otherwise clicks twice
set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
//placeMarker(event.latLng, map, results[0].formatted_address)
//alert();
if (marker == null) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
//marker = placeMarker(event.latLng, map, results[0].formatted_address) ;
} else {
marker.setPosition(event.latLng);
//infowindow.open(map, marker);
}
});
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
document.getElementById('departure_address').addEventListener('change', onChangeHandler);
document.getElementById('arrival_address').addEventListener('change', onChangeHandler);
}
function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
//alert(dep_lat);
$('#dep_lat').val(lat);
$('#dep_lng').val(lng);
$('#departure_address').val(address);
$('#clear_dep').show();
} else {
//alert(dep_lat);
if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
$('#arr_lat').val(lat);
$('#arr_lng').val(lng);
$('#arrival_address').val(address);
$('#clear_arr,.arrival_address').show();
}
}
if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function isEmpty(value) {
return (value == null || value.length === 0);
}
initMap_mobile();
#mobilemap {
height: 500px;
width: 100%;
border: solid 1px #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div class="cell-xs-12 mobw100 npr">
<div class="form-group text-right">
<label for="departure_address" class="form-label">From</label>
<input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<input type="hidden" name="dep_lat" id="dep_lat" value="">
<input type="hidden" name="dep_lng" id="dep_lng" value="">
</div>
</div>
<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
<div class="form-group text-right">
<label for="arrival_address" class="form-label">To</label>
<input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<input type="hidden" name="arr_lat" id="arr_lat" value="">
<input type="hidden" name="arr_lng" id="arr_lng" value="">
</div>
</div>
<div id="mobilemap"></div>
To hide the "click" marker (leaving the ones the DirectionsRenderer displays):
move the marker to the global scope (where the map variable is):
var map;
var marker;
hide the marker in the DirectionsService callback function when the route is displayed:
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
if (marker && marker.setMap) // hide click marker when directions displayed
marker.setMap(null);
} else {
alert('Directions request failed due to ' + status);
}
}
proof of concept fiddle
var map;
var marker; // move marker definition into the global scope
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService.route({
origin: {
query: document.getElementById('departure_address').value
},
destination: {
query: document.getElementById('arrival_address').value
},
travelMode: 'DRIVING'
},
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
if (marker && marker.setMap) // hide click marker when directions displayed
marker.setMap(null);
} else {
alert('Directions request failed due to ' + status);
}
});
}
function initMap_mobile() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('mobilemap'), {
mapTypeControl: false,
center: {
lat: 42.700000762939,
lng: 23.333299636841
},
zoom: 13
});
directionsRenderer.setMap(map);
var infowindow;
google.maps.event.addListener(map, 'click', function(event) {
//alert(marker.length);
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
}, function(results, status) {
//otherwise clicks twice
set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
if (marker == null) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
} else {
marker.setPosition(event.latLng);
}
});
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
document.getElementById('departure_address').addEventListener('change', onChangeHandler);
document.getElementById('arrival_address').addEventListener('change', onChangeHandler);
}
function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
//alert(dep_lat);
$('#dep_lat').val(lat);
$('#dep_lng').val(lng);
$('#departure_address').val(address);
$('#clear_dep').show();
} else {
if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
$('#arr_lat').val(lat);
$('#arr_lng').val(lng);
$('#arrival_address').val(address);
$('#clear_arr,.arrival_address').show();
}
}
if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function isEmpty(value) {
return (value == null || value.length === 0);
}
initMap_mobile();
#mobilemap {
height: 500px;
width: 100%;
border: solid 1px #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div class="cell-xs-12 mobw100 npr">
<div class="form-group text-right">
<label for="departure_address" class="form-label">From</label>
<input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<input type="hidden" name="dep_lat" id="dep_lat" value="">
<input type="hidden" name="dep_lng" id="dep_lng" value="">
</div>
</div>
<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
<div class="form-group text-right">
<label for="arrival_address" class="form-label">To</label>
<input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<input type="hidden" name="arr_lat" id="arr_lat" value="">
<input type="hidden" name="arr_lng" id="arr_lng" value="">
</div>
</div>
<div id="mobilemap"></div>
I am using Google Maps API V3 drag-able markers with auto-suggest in FROM and TO Field. After Clicking Show Route I get Map with 2 Markers A and B. If I change Marker A or B it Shows Updated Location in Navigation (directionsPanel). I need These Locations in FROM NEW MARKER ADDRESS: And TO NEW MARKER ADDRESS: Input fields when markers A and B dragged.A is for FROM and B is for TO Location. I searched on google and read API Details but did not find a solution. I need to insert these updated marker location (addresses) in Database for future references. Thanks in Advance.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Map Finalized</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#directionsPanel{
overflow-y:auto;
width:40%;
height:200px;
}
input[type="text"] {
width: 350px;
height:30px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var start_pos = new google.maps.LatLng(33.7167,73.0667);
function initialize() {
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(69.386,29.967),
new google.maps.LatLng(69.3451155,30.3753205)
);
var mapOptions = {
bounds:defaultBounds,
zoom:17,
center: start_pos
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var from = (document.getElementById('from'));
var to = (document.getElementById('to'));
var autocomplete = new google.maps.places.Autocomplete(from);
var autocomplete = new google.maps.places.Autocomplete(to);
autocomplete.bindTo('defaultBounds', map);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
codeAddress();
}
function calcRoute() {
var request = {
origin: document.getElementById('from').value,
destination: document.getElementById('to').value,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script>
$(document).ready(function(){
$('button').on('click',initialize);
});
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:60%; height:100%"></div>
<div id="from_to">
FROM: <input id="from" class="controls" type="text" placeholder="Enter a location">
<br/><br/><hr/>
TO: <input id="to" class="controls" type="text" placeholder="Enter a location">
<br/><hr/>
<button id="btn_refresh">Show route</button>
<p>Total Distance: <span id="total"></span></p>
</div>
NAVIGATION:
<div id="directionsPanel">
</div>
FROM NEW MARKER ADDRESS: <input type="text" id="addressmarker1" size="30">
<br/><br/><hr/>
TO NEW MARKER ADDRESS: <input type="text" id="addressmarker2" size="30">
</body>
</html>
Try this:
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
var directionsList = directionsDisplay.getDirections();
computeTotalDistance(directionsList);
document.getElementById("from").value = directionsList.routes[0].legs[0]["start_address"];
document.getElementById("to").value = directionsList.routes[0].legs[0]["end_address"];
});
You can also access other values:
//DISTANCE
document.getElementById("distance").value = directionsList.routes[0].legs[0]["distance"]["text"];
//DURATION
document.getElementById("duration").value = directionsList.routes[0].legs[0]["duration"]["text"];
//LATLNG POINT A
document.getElementById("fromLatLng").value = directionsList.routes[0].legs[0]["start_location"]["k"] + "," + directionsList.routes[0].legs[0]["start_location"]["B"] ;
//LATLNG POINT B
document.getElementById("toLatLng").value = directionsList.routes[0].legs[0]["end_location"]["k"] + "," + directionsList.routes[0].legs[0]["end_location"]["B"];
Please marked it solved if it helped
Do you have any idea why my directions service of Google Maps API doesn't work? It seems that method directionsService.route() isn't executed (cause alert with status is not displayed), but I don't know why. I'm newbie in Google Maps API and JS, so try to be forgiving, if it's something simple. :)
var map = null;
var pos = null;
const STORED_LOC = new google.maps.LatLng(50.405196, 11.894855);
var currentLat = document.getElementById("latLabel");
var currentLng = document.getElementById("lngLabel");
var additionalInfo = document.getElementById("additionalInfo");
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
pos = STORED_LOC;
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
options =
{
center: pos,
zoom: 15
}
marker = new google.maps.Marker(
{
position: pos,
map: map,
title: "Chosen localization"
}
);
map = new google.maps.Map(document.getElementById("mapContainer"), options);
marker.setMap(map);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
}
$("#yes").click(function () {
getPosition();
hideUserConsentSection();
});
$("#no").click(function () {
hideUserConsentSection();
showSetCustomLocationSection();
});
function showSetCustomLocationSection() {
$("#setCustomLocationSection").show();
}
function hideUserConsentSection() {
$("#userConsentSection").hide();
}
function getPosition() {
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 2000
}
navigator.geolocation.getCurrentPosition(showPosition, errorPosition, options);
}
else
{
additionalInfo.innerHTML += "Your browser doesn't support geolocation";
}
}
function showPosition(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
var request =
{
origin: STORED_LOC,
destination: pos,
travelmode: google.maps.TravelMode.DRIVING
}
directionsService.route(request, function(result, status)
{
alert(status);
if (status == google.maps.DirectionsStatus.OK)
{
alert("OKAY");
directionsDisplay.setDirections(result);
}
});
//map = new google.maps.Map(document.getElementById("mapContainer"), options);
//marker.setMap(map);
}
function errorPosition(position) {
switch (position.code) {
case 1:
showSetCustomLocationSection();
break;
case 2:
showSetCustomLocationSection();
break;
case 3:
showSetCustomLocationSection();
break;
default:
break;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
My HTML looks like that:
<h3>How to reach us?</h3>
<div id="userConsentSection">Can we use your geolocation?<br />
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" /><br /><br />
</div>
<div id="setCustomLocationSection" style="display:none">
Enter your geolocation. <br /><br />
<input type="text" id="customLocation" />
<input type="button" id="setCustomLocationButton" value="Show" /><br /><br />
</div>
<span>Latitude: </span>
<div id="latLabel">
</div>
<span>Longitude: </span>
<div id="lngLabel">
</div>
<div id="additionalInfo">
</div>
<div id="mapContainer" style="height: 400px; width: 100%">
</div>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=XXXX&sensor=true">
</script>
The answer is typo in request object - travelmode instead travelMode. This parameter is required and as the result - route method doesn't execute. Be careful with that name!
I have written an application where user can enter source and destination using Google places API auto complete and he also can enter an intermediate place . I just wanna determine whether that intermediate place come along the way of source and destination .
This code was working till last week . Not sure what is the issue .
Here is my code:
<html>
<head>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
</style>
<title>Pillion Search Engine</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places,geometry" type="text/javascript"></script>
<script type="text/javascript">
var locations = new Array();
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//calculates distance between two points in km's
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
function initialize() {
alert("Inside Initialize");
var UserSource = document.getElementById('searchTextFieldSource');
var UserDestination = document.getElementById('searchTextFieldDestination');
var DbSource = document.getElementById('searchTextFieldIntermediateSource');
var DbDestination = document.getElementById('searchTextFieldIntermediateDestination');
var ACUserSource = new google.maps.places.Autocomplete(UserSource);
var ACUserDestination = new google.maps.places.Autocomplete(UserDestination);
var ACDbSource = new google.maps.places.Autocomplete(DbSource);
var ACDbDestination = new google.maps.places.Autocomplete(DbDestination);
google.maps.event.addListener(ACDbDestination, 'place_changed', function () {
var place1 = ACUserSource.getPlace();
document.getElementById('city1').value = place1.name;
var place1Lat = place1.geometry.location.lat();
var place1Lng = place1.geometry.location.lng();
document.getElementById('cityLat1').value = place1Lat;
document.getElementById('cityLng1').value = place1Lng;
var obj = new Object();
obj.city = place1.name;
obj.latitude = place1.geometry.location.lat();
obj.longitude = place1.geometry.location.lng();
locations.push(obj);
var place2 = ACUserDestination.getPlace();
document.getElementById('city2').value = place2.name;
var place2Lat = place2.geometry.location.lat();
var place2Lng = place2.geometry.location.lng();
document.getElementById('cityLat2').value = place2Lat;
document.getElementById('cityLng2').value = place2Lng;
var obj = new Object();
obj.city = place2.name;
obj.latitude = place2.geometry.location.lat();
obj.longitude = place2.geometry.location.lng();
locations.push(obj);
//For intermediate point Source
var place3 = ACDbSource.getPlace();
document.getElementById('city3').value = place3.name;
var place3Lat = place3.geometry.location.lat();
var place3Lng = place3.geometry.location.lng();
document.getElementById('cityLat3').value = place3Lat;
document.getElementById('cityLng3').value = place3Lng;
//For intermediate point Destination
var place4 = ACDbDestination.getPlace();
document.getElementById('city4').value = place4.name;
var place4Lat = place4.geometry.location.lat();
var place4Lng = place4.geometry.location.lng();
document.getElementById('cityLat4').value = place4Lat;
document.getElementById('cityLng4').value = place4Lng;
var p1 = new google.maps.LatLng(place1Lat, place1Lng);
var p2 = new google.maps.LatLng(place2Lat, place2Lng);
//alert(calcDistance(p1, p2));
directionsDisplay = new google.maps.DirectionsRenderer();
var startPlace = new google.maps.LatLng(place1Lat, place1Lng);
var mapOptions = {
zoom: 7,
center: startPlace
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
var start = $("#city1").val();
var end = $("#city2").val();
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
var positionsource = new google.maps.LatLng(place3Lat, place3Lng);
var positiondestination = new google.maps.LatLng(place4Lat, place4Lng);
/*if(calcDistance(positiondestination, p1)> calcDistance(positiondestination, p2)) {
alert("Straight path");
}
else {
alert("Reverse path");
}*/
/*var heading1 = google.maps.geometry.spherical.computeHeading(p1, p2);
alert("heading1: " + heading1);
alert("heading2: " + heading2);*/
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
if ((google.maps.geometry.poly.isLocationOnEdge(positionsource,
new google.maps.Polyline({ path: google.maps.geometry.encoding.decodePath(result.routes[0].overview_polyline.points) }),
0.0100000000))&(google.maps.geometry.poly.isLocationOnEdge(positiondestination,
new google.maps.Polyline({ path: google.maps.geometry.encoding.decodePath(result.routes[0].overview_polyline.points) }),
0.0100000000)))
{
alert("Belongs to the path");
var heading2 = google.maps.geometry.spherical.computeHeading(positionsource, positiondestination);
if(heading2<0) {
alert("Reverse direction");
}
}
else {
alert("Doesnt Belong to the path");
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function refreshMap(locations) {
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(locations[0].latitude, locations[0].longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].city);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<body>
<div>
<b>Source A:</b><input id="searchTextFieldSource" type="text" size="50" placeholder="Enter the source" autocomplete="on" runat="server" />
<input type="text" id="city1" name="city1" />
<input type="text" id="cityLat1" name="cityLat1" />
<input type="text" id="cityLng1" name="cityLng1" />
</div>
<div>
<b>Destination B:</b><input id="searchTextFieldDestination" type="text" size="50" placeholder="Enter the destination" autocomplete="on" runat="server" />
<input type="text" id="city2" name="city2" />
<input type="text" id="cityLat2" name="cityLat2" />
<input type="text" id="cityLng2" name="cityLng2" />
</div>
<div>
<b>Intermediate Source C:</b><input id="searchTextFieldIntermediateSource" type="text" size="50" placeholder="Enter the destination" autocomplete="on" runat="server" />
<input type="text" id="city3" name="city3" />
<input type="text" id="cityLat3" name="cityLat3" />
<input type="text" id="cityLng3" name="cityLng3" />
</div>
<div>
<b>Intermediate Destination D:</b><input id="searchTextFieldIntermediateDestination" type="text" size="50" placeholder="Enter the destination" autocomplete="on" runat="server" />
<input type="text" id="city4" name="city4" />
<input type="text" id="cityLat4" name="cityLat4" />
<input type="text" id="cityLng4" name="cityLng4" />
</div>
<input id="clickMe" type="button" value="clickme" onclick="initialize();" />
<div id="map" style="width: 700px; height: 600px;"></div>
</body>
</html>