Example: getting the user position with HTML5 Geolocation API, then using google maps to find a route to the desired clicked location.
Last active
August 29, 2015 14:03
-
-
Save ffflabs/acad781594f9976839c3 to your computer and use it in GitHub Desktop.
Click on your desired destination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<meta charset="utf-8"> | |
<head> | |
<style> | |
#map-canvas { | |
height:600px; | |
width:900px; | |
} | |
</style> | |
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> | |
<script> | |
var map = null; | |
function initialize() { | |
map = new google.maps.Map(document.getElementById('map-canvas'), { | |
zoom: 14, | |
center: {lat: 41, lng: -89.5} | |
}); | |
var directionService= new google.maps.DirectionsService(); | |
var directionsDisplay = new google.maps.DirectionsRenderer(); | |
var getRoute=function (request) { | |
directionService.route(request, function (response, status) { | |
if (status == google.maps.DirectionsStatus.OK) { | |
directionsDisplay.setDirections(response); | |
directionsDisplay.setMap(map); | |
} else { | |
console.log('Not OK', response, status); | |
} | |
}); | |
}; | |
navigator.geolocation.getCurrentPosition(function (location) { | |
var lng=location.coords.longitude; | |
var lat=location.coords.latitude; | |
map.setCenter({lat:lat, lng:lng}); | |
var originMarker=new google.maps.Marker({position:{lat:lat, lng:lng}, | |
map:map, | |
title:'This is your position' | |
}); | |
google.maps.event.addListener(map,'click',function(mouseEvent) { | |
console.log('clicked on ',mouseEvent.latLng.lat(), mouseEvent.latLng.lng()); | |
var destinationMarker= new google.maps.Marker({ position:mouseEvent.latLng, | |
map:map, | |
title:'This is your destination', | |
draggable:true, | |
clickable:true | |
}); | |
var request = { origin: originMarker.getPosition(), | |
destination: destinationMarker.getPosition(), | |
travelMode: 'DRIVING', | |
}; | |
getRoute(request); | |
}); | |
}); | |
} | |
google.maps.event.addDomListener(window, 'load', initialize); | |
</script> | |
</head> | |
<body> | |
<h4>Click on your desired destination</h4> | |
<div id="map-canvas" width="900" height="600"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment