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!
Related
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>
When I ask google for directions, both "MMU" and "MMU Airport" work fine, but when I use the API it keeps going to MLU airport... what gives?
Code:
var directionService = new google.maps.DirectionsService;
var geocoder = new google.maps.Geocoder;
directionService.route({
origin: $('#selAirport').val() + ' Airport',
destination: $('#selZIPZone').val(),
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
console.log(response, status);
...
dev-tools photo showing it received "MMU Airport" as the origin, but set the Start Address to MLU Airport instead
That looks like a data problem. The directions service/geocoder recognize Morristown Municipal Airport, but not MMU. I reported that through the Google Maps "report an error" (lower right hand corner of the map), not sure if it will be accepted.
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionService.route({
origin: 'Morristown Airport',
destination: "Florham Park , NJ",
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + 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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Taking into account your last comment it looks like you have an autocomplete of places library. In this case you can retrieve the place ID from the autocomplete element and pass it to directions service. This way you will be sure that directions service is working with an exact choice of the user.
Please look at this example and use autocomplete to search your route:
http://jsbin.com/xuyisem/edit?html,output
code snippet:
var directionsDisplay;
var directionsService;
var map;
var placeId1, placeId2;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
var mapOptions = {
zoom:10,
center: new google.maps.LatLng(32.5101466,-92.0436835)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var inputFrom = document.getElementById('from');
var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, {});
autocompleteFrom.bindTo('bounds', map);
autocompleteFrom.addListener('place_changed', function() {
var place = autocompleteFrom.getPlace();
placeId1 = place.place_id;
});
var inputTo = document.getElementById('to');
var autocompleteTo = new google.maps.places.Autocomplete(inputTo, {});
autocompleteTo.bindTo('bounds', map);
autocompleteTo.addListener('place_changed', function() {
var place = autocompleteTo.getPlace();
placeId2 = place.place_id;
});
}
function calcRoute() {
if (!placeId1) {
alert("Please select origin");
return;
}
if (!placeId2) {
alert("Please select destination");
return;
}
var start = {
placeId: placeId1
};
var end = {
placeId: placeId2
};
var request = {
origin: start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: false
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<input type="text" name="from" id="from" placeholder="Select origin" />
<input type="text" name="to" id="to" placeholder="Select destination" />
<input type="button" name="calcroute" value="Get route" onclick="calcRoute();return false;" />
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initialize"></script>
I have this code of google map with coordinates values
the questions is how we can merge the text field of Lat & Lon into one field only,
so we need one text field only display the coordinated (Lat,Lon)
can any one help
the code is below
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?
sensor=false"></script>
<br />
Copy this number and past it in GPS field
<br />
<br />
<input id="divLon" type="text" />
<input id="divLat" type="text" />
<br />
<br />
<div id="map_canvas" style="width: 600px; height: 600px;"></div>
<script type="text/javascript">
var marker;
function initialize() {
var lat;`enter code here`
var lon;
navigator.geolocation.getCurrentPosition(function (location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId:
google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function (event) {
update();
});
update();
}, function (positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, { enableHighAccuracy: true });
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLon = document.getElementById ("divLon");
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ();
divLon.value = lonlan.lng ();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfpx62iYkjhpz0J-
vu4Zz96vtWE2TFzQs&signed_in=true&callback=initMap"></script>
</body>
</html>
Try this code:
function update() {
var lonlan = marker.getPosition();
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ()+", "+lonlan.lng ();
}
Simplest solution, use the .toUrlValue method of a google.maps.LatLng
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
code snippet:
var marker;
function initialize() {
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function(event) {
update();
});
update();
}, function(positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, {
enableHighAccuracy: true
});
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="divLatLon" />
<div id="map_canvas"></div>
I am new to Angular and loving it. I have been diving deeper and being successful until this particular depth.
I forked a workable code which largely meets my needs from (http://kcy.me/1bbra).
Everything works fine. However the maps doesn't display. I went into chrome's console to debug and everything seems fine. The maps is loading and responding to the buttons but not displaying.
After many of hours of debugging, i found out that when i initialized my session the maps doesn't display, when i comment out the session code, everything works fine.
See my code here
This is the code on my dashboard
<?php
require '../scripts/master.php';
$logs = new authenticate();
$logs->page_protect();
//just collecting data from specified table
$rows = $logs->getFilteredDetails("user_info","app_id",$_SESSION['my_user_id']);
//assessing individual records
$my_user_id = $rows['user_id'];
?>
The page protect function from the authenticate class
function page_protect()
{
session_start();
if (!isset($_SESSION['my_user_id']))
{
header("Location: ../login.php");
}
}
This is the section which displays the maps on my dashboard page
<section class="content">
<div ng-controller="MapCtrl">
<div class="map_container">
<google-map center="map.center" zoom="map.zoom" draggable="true" options="map.options" control="map.control">
<markers models="map.markers" coords="'self'" options="'options'" isLabel='true'>
</markers>
</google-map>
</div>
<div class="controls">
<h3>Current location</h3>
<p>
<button ng-click="addCurrentLocation()">Current location</button>
</p>
<h3>Address search</h3>
<p>
<input type="text" placeholder="Address. i.e: Concha Espina 1, Madrid" ng-model="address" style="width: 210px"/>
<button ng-click="addAddress()">Look up!</button>
</p>
<p>
Source Code
</p>
</div>
</div>
</section>
And finally, the angular code
var app = angular.module('AngularGoogleMap', ['google-maps']);
app.factory('MarkerCreatorService', function () {
var markerId = 0;
function create(latitude, longitude) {
var marker = {
options: {
animation: 1,
labelAnchor: "28 -5",
labelClass: 'markerlabel'
},
latitude: latitude,
longitude: longitude,
id: ++markerId
};
return marker;
}
function invokeSuccessCallback(successCallback, marker) {
if (typeof successCallback === 'function') {
successCallback(marker);
}
}
function createByCoords(latitude, longitude, successCallback) {
var marker = create(latitude, longitude);
invokeSuccessCallback(successCallback, marker);
}
function createByAddress(address, successCallback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
invokeSuccessCallback(successCallback, marker);
} else {
alert("Unknown address: " + address);
}
});
}
function createByCurrentLocation(successCallback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var marker = create(position.coords.latitude, position.coords.longitude);
invokeSuccessCallback(successCallback, marker);
});
} else {
alert('Unable to locate current position');
}
}
return {
createByCoords: createByCoords,
createByAddress: createByAddress,
createByCurrentLocation: createByCurrentLocation
};
});
app.controller('MapCtrl', ['MarkerCreatorService', '$scope', function (MarkerCreatorService, $scope) {
MarkerCreatorService.createByCoords(40.454018, -3.509205, function (marker) {
marker.options.labelContent = 'Autentia';
$scope.autentiaMarker = marker;
});
$scope.address = '';
$scope.map = {
center: {
latitude: $scope.autentiaMarker.latitude,
longitude: $scope.autentiaMarker.longitude
},
zoom: 12,
markers: [],
control: {},
options: {
scrollwheel: false
}
};
$scope.map.markers.push($scope.autentiaMarker);
$scope.addCurrentLocation = function () {
MarkerCreatorService.createByCurrentLocation(function (marker) {
marker.options.labelContent = 'You´re here';
$scope.map.markers.push(marker);
refresh(marker);
//alert("I reached");
});
};
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address, function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
function refresh(marker) {
$scope.map.control.refresh({latitude: marker.latitude,
longitude: marker.longitude});
}
}]);
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>