For the start, i will key in origin and destination and it will show the displayed route from origin A to destination B. However, i would like to make the origin A draggable such that it will recalculate the route and display to me.
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 1.317206, lng: 103.772240},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('destination-input').addEventListener('change',
onChangeHandler);
}
function calculateAndDisplayRoute(directionsService,
directionsDisplay) {
var start = document.getElementById('origin-input').value;
var end = document.getElementById('destination-input').value;
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
}
});
}
The HTML code is provided below.
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="map"></div>
</body>
Below is the screenshot of the current project i have.
Screenshot
Please try:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
Related
Hi I'm using google documentation in geocoding service.
The script should display the location Casablanca but it still show the default location in austalia
The problem is that geocoder.geocode(...) is not executed
function initMap() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
scrollwheel: false,
zoom: 8,
});
codeAddress(geocoder,map);
}
function codeAddress(geocoder, map)
{
var addr = "Casablanca";
geocoder.geocode( {'addr':addr}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.addr);//center the map over the result
//place a marker at the location
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.addr
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
PS:
I'm using GooglMapper https://github.com/bradcornford/Googlmapper
I appreciate any help.
geocoder.geocode( {'addr':addr}, function(results, status)
Should be:
geocoder.geocode( {'address':addr}, function(results, status)
The GeocoderRequest object literal contains the following fields:
{
address: string,
location: LatLng,
placeId: string,
bounds: LatLngBounds,
componentRestrictions: GeocoderComponentRestrictions,
region: string
}
Taken from the documentation
Answer For my problem
map.setCenter(results[0].geometry.addr);
Should be
map.setCenter(results[0].geometry.location);
And
position: results[0].geometry.addr
Should Be
position: results[0].geometry.location
i am not able get more than one possible routes from source to destination.
Here is jsfillder which also used for single line draw but i want to draw for multiple possible route.
code snippet (from fiddle above):
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var myOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var waypts = [];
stop = new google.maps.LatLng(51.943571, 6.463856)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(51.945032, 6.465776)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(51.945538, 6.469413)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(51.947462, 6.467941)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(51.945409, 6.465562)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(51.943700, 6.462096)
waypts.push({
location: stop,
stopover: true
});
start = new google.maps.LatLng(51.943382, 6.463116);
end = new google.maps.LatLng(51.943382, 6.463116);
createMarker(start);
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
initialize();
#map-canvas {
height: 400px;
}
<script src="http://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
The general answer is use provideRouteAlternatives:true, however you can't get alternative routes with waypoints, the directions service won't provide them.
I'm new to Google Maps Javascript API and doing some basic things. I want to show a day trip route of Yellowstone National Park. The start point is West Thumb Geyser Basin, end point is Norris Geyser Basin, as the code showing below (saved as a html file).
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function init() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng({lat: 44.427963, lng: -110.5906437}),// Yellowstone National Park
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: {lat: 44.4170394, lng: -110.5740972}, // West Thumb Geyser Basin,
destination: {lat: 44.7262344, lng: -110.7217907}, // Norris Geyser Basin,
travelMode: google.maps.TravelMode.DRIVING,
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<font size=2><b>Yellowstone National Parks</b></font>
<div id=googleMap style="width:1100px;height:800px;"></div>
</body>
</html>
But the route returned is not an optimal one.
Please see the returned route here
Seems it's a Google Maps JavaScript API bug? Any idea/thought? Thanks in advance.
Updated code. another funny thing. Without optimizedWaypoints, it's working fine.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function init() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng({lat: 44.427963, lng: -110.5906437}),// Yellowstone National Park
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var wayPoints = [{ location: {lat: 44.4604826, lng: -110.8303263}, stopover: true }, { location: {lat: 44.525086, lng: -110.840378}, stopover: true }]; // Old Faithful Geyser and Grand Prismatic Spring
directionsService.route({
origin: {lat: 44.4170394, lng: -110.5740972}, // West Thumb Geyser Basin,
destination: {lat: 44.7262344, lng: -110.7217907}, // Norris Geyser Basin,
waypoints: wayPoints,
//optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING,
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<font size=2><b>Yellowstone National Parks</b></font>
<div id=googleMap style="width:1100px;height:800px;"></div>
</body>
</html>
It is not going to be able to optimize the order of the waypoints (you only have one waypoint). The optimizeWaypoints option only rearranges the waypoints, it won't change the start or the destination.
from the documentation:
By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the Travelling Salesman Problem.) All waypoints must be stopovers for the Directions service to optimize their route.
I need some help with the Google Maps WEb JS API. I'm diving into it for the first time and now I'm stuck.
I want to set a static direction of two static markers on a Google Map.
I'm trying to write the code in OOP.
The map is getting load on my webpage, but I'm not getting to see the "markers" and the "direction".
Please some help and advice!
var WEB = WEB || {};
(function() {
'use strict'
//controller init object
WEB.controller = {
init: function() {
// initialize APP objects
google.maps.event.addDomListener(window, 'load', WEB.googleMaps.init());
}
};
WEB.googleMaps = {
init: function() {
WEB.googleMaps.directionsDisplay();
console.log('1. init directionsDisplay');
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(52.295042, 4.867158),
zoom: 14,
maxZoom: 15,
minZoom: 13,
draggable: false
});
console.log('2. init map');
WEB.googleMaps.directionsDisplay(map);
console.log('3. init directionsDisplay in map');
console.log('4. init calc route');
WEB.googleMaps.calcRoute();
},
directionsDisplay: function() {
new google.maps.DirectionsRenderer();
},
directionsService: function(){
new google.maps.DirectionsService();
},
calcRoute: function() {
WEB.googleMaps.directionsService();
console.log('5. init directionsService');
var start = new google.maps.LatLng(XX.XXXXXX, XX.XXXXXX);
var end = new google.maps.LatLng(XX.XXXXXX, XX.XXXXXX);
console.log('6. set directions', start, end);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
console.log('7. put directions in the service', request);
WEB.googleMaps.directionsService(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log('7. DirectionsStatus is OK');
WEB.googleMaps.directionsDisplay(response);
}
});
}
};
WEB.controller.init();
})();
<!DOCTYPE html>
<html lang="nl">
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- GOOGLE MAPS API -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
</head>
<body class="">
<header class="">
</header>
<main class="">
<div id="map-canvas" style="width: 100%; height: 500px; margin:0; padding:0; border:0;">
</div>
</main>
</body>
</html>
You need to do something more like this.
WEB.googleMaps = {
init: function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(52.295042, 4.867158),
zoom: 14,
maxZoom: 15,
minZoom: 13,
draggable: false
});
var directionsDisplay = WEB.googleMaps.getDirectionsDisplay(map);
WEB.googleMaps.calcRoute(directionsDisplay);
},
getDirectionsDisplay: function(map) {
return new google.maps.DirectionsRenderer({map: map});
},
getDirectionsService: function(){
return new google.maps.DirectionsService();
},
calcRoute: function(directionsDisplay) {
var directionsService = WEB.googleMaps.getDirectionsService();
var start = new google.maps.LatLng(XX.XXXXXX, XX.XXXXXX);
var end = new google.maps.LatLng(XX.XXXXXX, XX.XXXXXX);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
};
WEB.controller.init();
It helps to read this carefully:
https://developers.google.com/maps/documentation/javascript/directions
In a web page I have multiple google maps generated in a loop. And I am using the google directions api to display directions on each of the maps. The problem is that this code is displaying all the directions on the last map. Have any ideas?:
var currentPosition = new google.maps.LatLng(44.462691,26.1215866);
var directionsService = new google.maps.DirectionsService();
function DisplayLocations(){
$("#mapsContainer").empty();
for(var i=0;i<locationsDisplayed;i++){
var location=locationsArray[i];
$("#mapsContainer"+i).append('<div id="ImageMap'+i+'" style="width=250px;height:200px;"></div>');
var myOptions = {
zoom: 14,
center: currentPosition,
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('ImageMap'+i),myOptions);
var request = {
origin: currentPosition,
destination: location.position,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
RenderDirection(map,response);
}
});
}
}
function RenderDirection(map,result) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
Yes, your directionsService gets overwritten in the loop.
What you can do, is chain the requests. So, whenever a response returns, you trigger the next request.
<html>
<head>
<title>Javascript, multiple google maps on same page(Directions Renderer is not working as excepted)</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var maps = []; // we will copy (the reference to) every map to this array, so we can always access them at will
var locationsArray = [
{position: new google.maps.LatLng(44.460, 26.120) },
{position: new google.maps.LatLng(44.461, 26.121) },
{position: new google.maps.LatLng(44.462, 26.122) },
{position: new google.maps.LatLng(44.463, 26.123) }
]
var currentPosition = new google.maps.LatLng(44.462691, 26.1215866);
function DisplayLocations() {
$("#mapsContainer").empty();
nextLocation(0); // we don't use a for-loop; we wait for a response to trigger the next request
function nextLocation(i) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var location=locationsArray[i];
$("#mapsContainer"+i).append('<div id="ImageMap'+i+'" style="width=250px;height:200px;"></div>');
var myOptions = {
zoom: 14,
center: currentPosition,
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('ImageMap'+i), myOptions);
maps.push(map);
var request = {
origin: currentPosition,
destination: location.position,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
RenderDirection(maps[i++], response, directionsDisplay);
// if there is a next location, we will fire a new request
if (locationsArray[i]) {
nextLocation(i);
}
}
});
}
}
function RenderDirection(map, response, directionsDisplay) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
}
google.maps.event.addDomListener(window, 'load', DisplayLocations);
</script>
<style>
.map {
height: 210px;
width: 260px;
float: left;
margin: 2px;
}
</style>
</head>
<body>
<div class="map" id="mapsContainer0"></div>
<div class="map" id="mapsContainer1"></div>
<div class="map" id="mapsContainer2"></div>
<div class="map" id="mapsContainer3"></div>
</body>