Google gave an example
http://googlemapsapi.blogspot.com/2007/05/driving-directions-support-added-to.html
Is the source code available somewhere or a tutorial on that precise example ?
Here's a very basic example using the v3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
<div id="map" style="width: 280px; height: 400px; float: left;"></div>
<div id="panel" style="width: 300px; float: right;"></div>
</div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: 'Chicago',
destination: 'New York',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
Screenshot:
Code to get route, legs and other data using Latitude/longitude OR using Address without google map in JavaScript using v3 API:
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=<key>&libraries=places"></script>
<script>
var directionsService = new google.maps.DirectionsService();
var start_lat = "41.8781136";
var start_lon = "-87.6297982";
var end_lat = "40.7127753";
var end_lon = "-74.0059728";
// Using Latitude and longitude
var request = {
origin: new google.maps.LatLng(start_lat, start_lon),
destination: new google.maps.LatLng(end_lat, end_lon),
optimizeWaypoints: true,
avoidHighways: false,
avoidTolls: false,
travelMode: google.maps.TravelMode.DRIVING
};
//Using plain address
// var request = {
// origin: { query: "Chicago, IL, USA" },
// destination: { query: "New York, NY, USA" },
// travelMode: google.maps.TravelMode.DRIVING,
// };
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var leg = response.routes[0].legs[0];
var polyline = route.overview_polyline;
var distance = route.legs[0].distance.value;
var duration = route.legs[0].duration.value;
console.log(route); // Complete route
console.log(distance); // Only distance
console.log(duration); // Only duration
console.log(leg); // Route options/list
console.log(polyline); // Polyline data
}
});
</script>
Related
I'm trying to get the Google Maps Javascript API working, and I've copied the tutorial and directions code, but I can't get directionsService.route to work. Here is my code.
var directionsDisplay;
var directionsService;
var map;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({map:map});
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:9,
center: chicago
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
console.log(google.maps);
console.log(directionsDisplay);
console.log(directionsService);
console.log(directionsService.route);
}
$(document).ready(function() {
function calcRoute() {
// console.log(map);
var start = document.getElementById("origin").value;
var end = document.getElementById("destination").value;
console.log('start');
console.log(start);
console.log('end');
console.log(end);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
console.log(google.maps);
console.log(google.maps.DirectionsService);
console.log(directionsDisplay);
console.log(directionsService);
console.log(directionsService.route);
directionsService.route(request, function (result, status) {
console.log('hi');
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
$('#origin-search').submit(function() {
console.log('calling calcRoute');
calcRoute();
});
});
The console.log('hi') statement is never reached. Attached are the log statements from the console. I first load index, then do the $('#origin-search').submit(), then rerouted back to loading index. Note that the directionsService.route function logs differently inside initialize() than inside calcRoute().
If I move calcRoute into $(document).ready I get errors because the map isn't initialized yet. I would call calcRoute only after you are sure the map has been initialized.
Here is some working code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions Display</title>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var directionsDisplay;
var directionsService;
var map;
function initMap() {
directionsService = new google.maps.DirectionsService;
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: chicago
});
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
calcRoute();
}
function calcRoute() {
var start = "cambridge, ma";
var end = "boston, ma";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
I'm working with Google Maps to show a cars last location. Often times this will be in a parking lot off of a main road, however when I input the coordinates for the parking lot carLatLng into Google's routing engine the response I get looks to be the nearest road. How do I get it so that the same coordinates I enter are the ones I get from my response?
var carLatLng = new google.maps.LatLng(29.9461,-90.07)
var request = {
origin: carLatLng,
destination:
waypoints: [],
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.WALKING
};
self.directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var lat = response.routes[0].legs[0].end_location.lat();
var lng = response.routes[0].legs[0].end_location.lng();
// lat = 29.946164
// lng = -90.0702933
}
});
The DirectionsService always returns start/end points for driving directions on the road. If you want the result to end somewhere else, you need to extend the polyline yourself (you have the original coordinates, draw a polyline from there to the end of the route from the directions service).
proof of concept fiddle
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 carLatLng = new google.maps.LatLng(29.9461, -90.07);
var carMarker = new google.maps.Marker({
map: map,
position: carLatLng
});
var request = {
origin: "Dixon, New Orleans, LA",
destination: carLatLng,
waypoints: [],
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.WALKING
};
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
polylineOptions: {
strokeColor: "#0000FF"
}
})
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var lat = response.routes[0].legs[0].end_location.lat();
var lng = response.routes[0].legs[0].end_location.lng();
directionsRenderer.setDirections(response);
map.setCenter(carLatLng);
map.setZoom(20);
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "#0000FF",
path: [carLatLng, response.routes[0].legs[0].end_location]
});
// lat = 29.946164
// lng = -90.0702933
}
});
}
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"></script>
<div id="map_canvas"></div>
I've done a lot lately with Google Map API, unfortunately not with the routing service.
But have a look at these tutorials, they are quite detailed, I found them very helpful at times: http://econym.org.uk/gmap/
For your case I'd especially look at part 26 onwards.
I'm using google maps directions api to draw traffic information on map. I want to show my custom traffic info, for both driving directions on one street.
When I request the directions from A to B and from B to A, it renders the 2 routes overlapped, so actually it only shows one route.
var list = [
{ origin: new google.maps.LatLng(41.13021, 16.83124), destination: new google.maps.LatLng(41.12813, 16.83778), color: 1},
{ origin: new google.maps.LatLng(41.12813, 16.83778), destination: new google.maps.LatLng(41.13021, 16.83124), color: 2}
];
function calcRoute(entry) {
var request = {
origin: entry.origin,
destination: entry.destination,
travelMode: google.maps.TravelMode["DRIVING"]
};
if (entry.color == 1){
vStrokeColor = "#FF0000"
vzIndex = 100
}else if (entry.color == 2){
vStrokeColor = "#0DFF00"
vzIndex = 1
}
var directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions:{suppressPolylines:true, geodesic:true, strokeColor:vStrokeColor, strokeWeight: 4, strokeOpacity: 1, zIndex: vzIndex}});
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
Is there a way to achieve this with Google Apis?
Thanks.
UPDATE: Correct GPS coordinates
var list = [
{ origin: new google.maps.LatLng(41.13021, 16.83124), destination: new google.maps.LatLng(41.12813, 16.83778), color: 1},
{ origin: new google.maps.LatLng(41.12813, 16.83778), destination: new google.maps.LatLng(41.13021, 16.83124), color: 2}
];
var vStrokeColor;
var vzIndex;
var map;
var directionsService = new google.maps.DirectionsService();
function calcRoute(entry) {
var request = {
origin: entry.origin,
destination: entry.destination,
travelMode: google.maps.TravelMode["DRIVING"]
};
if (entry.color == 1){
vStrokeColor = "#FF0000"
vzIndex = 100
}else if (entry.color == 2){
vStrokeColor = "#0DFF00"
vzIndex = 1
}
var directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions:{suppressPolylines:true, geodesic:true, strokeColor:vStrokeColor, strokeWeight: 4, strokeOpacity: 1, zIndex: vzIndex}});
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function initialize() {
var myLatlng = new google.maps.LatLng(41.08801, 16.83689);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
calcRoute(list[0]);
calcRoute(list[1]);
}
google.maps.event.addDomListener(window,'load',initialize);
html,body,#map {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js">
</script>
<div id="map"></div>
I am creating a wp8 application , and I am using this html code to display 2 pushpins and the directions between them but the problem is that the directions are displayed without the map (on the emulater the html page is all displayed without problem).
There is my Html code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Amex</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var ksa = new google.maps.LatLng(24.7116667, 46.7241667);
function initialize() {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: ksa
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(23.7116667, 45.7241667),
destination: new google.maps.LatLng(20.7116667, 45.7241667),
travelMode: google.maps.DirectionsTravelMode.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 (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById("total").innerHTML = total + " km";
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:80%"></div>
<div id="directionsPanel" style="width:100%;height 20%;font-family:arial">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</div>
</body>
</html>
I have find the solution It is just need to replace this
<div id="map_canvas" style="width:100%; height:80%"></div>
by this
<div id="map_canvas" style="width:300px; height:480px"></div>
If a user has disabled the location feature or if he uses a non geo supported feature.
How to do this programatically? This will get executed,if i enable geo location in my browser ,if i do not enable,i want some other code to get executed.Where i put that other code which will be executed when i do not enable or use non supported browser.
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
I would use modernizer to sniff out whether the browser supports geolocation and then take the appropriate action.
if (Modernizr.geolocation) {
//do geolocation/gmaps stuff
} else {
//do something else
}
You can even load shims to give the geolocation functionality to browsers which don't support it. There are examples in the modernizer documentation section.
e.g.
Modernizr.load({
test: Modernizr.geolocation,
yep : 'geo.js',
nope: 'geo-polyfill.js'
});
--Edit
<html>
<head>
<script type="text/javascript" src="modernizer.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=&sensor=true"></script>
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
if (Modernizr.geolocation) {
// Do the geolocation
navigator.geolocation.getCurrentPosition(initializeGeo, handle_error);
} else {
// No geolocation path
initializeNonGeo();
}
}
function handle_error(err) {
alert("Geolocation could not be run");
if (err.code == 1) {
alert("user denied");// user said no!
}
initializeNonGeo();
}
function initializeGeo() {
alert("has geolocation");
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function initializeNonGeo() {
alert("no geolocation"); //do non geo stuff.
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</html>