Skip to content

Instantly share code, notes, and snippets.

@sotoz
Last active March 2, 2016 09:37
Show Gist options
  • Save sotoz/591fb56fb3f7d2fa00d8 to your computer and use it in GitHub Desktop.
Save sotoz/591fb56fb3f7d2fa00d8 to your computer and use it in GitHub Desktop.
Google maps geolocation get directions
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=123&sensor=false&language=el"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(40.392581, 21.549683)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
function getLocation(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
callback({
lat: position.coords.latitude,
lon: position.coords.longitude
});
},function (error) {
alert("Location not found");
});
} else {
alert("Location not found");
}
}
function getStart(callback) {
var start = document.getElementById('start').value;
if (start == "my_location") {
getLocation(function (loc) {
start = new google.maps.LatLng(loc.lat, loc.lon);
callback(start);
});
} else {
callback(start);
}
}
function calcRoute() {
var end = document.getElementById('end').value;
if (end != "") {
getStart(function (start) {
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);
}
});
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<select id="start" onchange="calcRoute();">
<option value="my_location">Η τοποθεσία μου</option>
<option value="Thessaloniki, Ελλάδα">Θεσσαλονίκη</option>
<option value="Αθήνα, Ελλάδα">Αθήνα</option>
<option value="Πάτρα, Αχαΐα, Ελλάδα">Πάτρα</option>
</select>
<select id="end" onchange="calcRoute();">
<option value="">Επιλέξτε</option>
<option value="Γρεβενά, Ελλάδα">Γρεβενά</option>
<option value="Καστοριά, Ελλάδα">Καστοριά</option>
<option value="Κοζάνη, Ελλάδα">Κοζάνη</option>
<option value="Φλώρινα, Ελλάδα">Φλώρινα</option>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment