Going from location a to b using HTML5 Geolocation!
In this tutorial, our goal is to get directions from the nearest store like a Starbucks to the next closest one.
Important: to follow through this tutorial, you may need to make minor adjustments to the JS codes as the latest version of Google API might be different.
Use SimpleGeo’s Places API to find the closest Starbucks to the user’s current location and then, once that location is set, make a second API call to SimpleGeo to find the next closest Starbucks location. Then use the Google Maps API to give directions from the first Starbucks to the second Starbucks.
To begin, add the SimpleGeo API to the collection of JavaScript libraries:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://j.maxmind.com/app/geoip.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
</script>
<script src="http://cdn.simplegeo.com/js/1.2/simplegeo.places.jq.min.js">
</script>
SimpleGeo is free, but it does require you to sign up to get an API key. Once you’ve signed up, you can find the API key by clicking the Tokens menu and then the JSONP Tokens submenu.
Add your website domain(s) to the allowed domains list. This prevents other people from using your API key. Now copy the key and replace the placeholder at the top of our sample’s JavaScript:
// SimpleGeo globals:
var geoclient = new simplegeo.PlacesClient(‘REPLACE WITH YOUR API KEY’);
// Google Maps globals: var directionRenderer;
var directionsService = new google.maps.DirectionsService(); var map;
$(document).ready(function () {
// Set up map starting point for Google Maps.
// Set initial coords to latitude −92 and longitude 32, which is somewhere
// around Kansas City in the center of the US, and then set the zoom to 4
// so the entire US is visible and centered. var kansas = new google.maps.LatLng(32, −92); var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP, center: kansas
}
map = new google.maps.Map(document.getElementById(“map”), myOptions);
directionsRenderer = new google.maps.DirectionsRenderer(); directionsRenderer.setMap(map);
// wire up button click
$(‘#go’).click(function () {
// Use our new getLatLng with fallback and define an inline function
// to handle the callback.
getLatLng(function (latitude, longitude, isMaxMind) {
// use SimpleGeo to get closest Starbucks var query = “Starbucks”;
geoclient.search(latitude, longitude, { q: query, radius: 20, num: 1 }, function (err, dataStart) {
if (err) {
error(err);
} else {
// We only asked for one result and SimpleGeo returns results
// based on distance so the closest is first, so make sure we
// got a result.
if (dataStart.features.length == 1) {
// save start coordinates and address var startLat =
dataStart.features[0].geometry.coordinates[1]; var startLng =
dataStart.features[0].geometry.coordinates[0]; var startAddress =
dataStart.features[0].properties[‘address’];
// save in Google LatLng as well
var start = new google.maps.LatLng(startLat, startLng);
// look up the closest Starbucks to the one we just found geoclient.search(startLat, startLng, { q: query, radius:
20, num: 2 }, function (err, dataEnd) { if (err) {
error(err);
} else {
// This time we asked for two results; the first
// result should be the starting Starbucks,
// so this time access the second result. if (dataEnd.features.length == 2) {
// save end coordinates and address var endLat =
dataEnd.features[1].geometry.coordinates[1]; var endLng =
dataEnd.features[1].geometry.coordinates[0]; var endAddress =
dataEnd.features[1].properties[‘address’];
// save in Google LatLng as well
var end = new google.maps.LatLng(endLat, endLng);
// Now add directions from starting Starbucks
// to ending one.
// Set the request options: var request = {
origin: start, destination: end, travelMode:
google.maps.DirectionsTravelMode.DRIVING
};
// make the directions request directionsService.route(request, function
(result, status) { if (status ==
google.maps.DirectionsStatus.OK) {
// Display the directions using
// Google’s Directions Renderer. directionsRenderer.
setDirections(result);
// output info separately
$(‘#info’)/(‘Closest Starbucks:
<strong>’ + startAddress
+ ‘</strong><br />’ + ‘Next Starbucks: <strong>’ + endAddress
+ ‘</strong>’);
} else {
error(“Directions failed due to: ” + status);
}
});
}
else {
error(‘Could not find a Starbucks near ‘ + startAddress);
}
}
});
}
else {
error(‘Could not find a Starbucks near you.’);
}
}
});
// if we used MaxMind for location, add attribution link if (isMaxMind) {
$(‘body’).append(‘<p><a href=”http://www.maxmind.com” target=”_blank”>IP to Location Service Provided by MaxMind</a></p>’);
}); } = });
});
function getLatLng(callback) {
// test for presence of geolocation
if (navigator && navigator.geolocation) {
// make the request for the user’s position navigator.geolocation.getCurrentPosition(function (position) {
// success handler
callback(position.coords.latitude, position.coords.longitude);
},
function (err) {
// handle the error by passing the callback the location from MaxMind callback(geoip_latitude(), geoip_longitude(), true);
});
} else {
// geolocation not available, so pass the callback the location from
// MaxMind
callback(geoip_latitude(), geoip_longitude(), true);
}
}
function error(msg) { alert(msg);
}
How it works
Other than the call to simplegeo.PlacesClient() to set up SimpleGeo, the code starts off as a normal HTML5 Geolocation code.
In the click handler, we get the user’s current location using the getLatLng() function and we use the resulting latitude and longitude to call the SimpleGeo geoclient. search() function to find the closest Starbucks to us. The geoclient.search() function takes in latitude and longitude parameters, our query options, and a callback function.
We set the query options to a search term (q param) of Starbucks within a 20-kilometer radius (radius param), and indicate that only one result (num param) is required.
The callback returns a feature collection, which contains various information about each search result (including latitude and longitude). In the callback, we save the latitude, longitude, and address in variables as our starting location.
Then we make a second geoclient.search() call using the starting location as the reference point. This time it returns two results, since the first result is still the starting location. We store the second feature item’s latitude, longitude, and address in the ending location variables.
Now that the start and end locations are set, we can use the same Google Maps API call as in the last example to display the driving directions between the two locations.To finish off the example, we display the starting and ending addresses above the map.
Here is the list of other related tutorials that are highly recommended:
- Develop Multi-thread JavaScript applications with Web Workers
- Getting direction from a location via HTML5 Geolocation
- Harness the power of HTML5 custom data via JavaScript API
- Develop bidirectional browser-server applications with HTML5 WebSocket API
- How to make a webpage with partial dynamic content update accessible via HTML5 ARIA live
- Build Guess The Number Game With JavaScript
- Build advance single page application with Angular and Boostrap
- How Bootstrap 4 extensible content containers or Cards work
- Comprehensive overview of Bootstrap 4 features for user interface customizations
- Intro to real-time bidirectional communications between browsers and webSocket servers
- Intro to functional reactive programming for advance js web development
Here is the list of classes that are highly recommended:
- Introduction to Content Management System courses like WordPress, Joomla or Drupal
- Learn PHP and MySQL for building dynamic websites like e-commerce
- Hands-on advance JS coding with Ajax and JSON
- Master popular JS frameworks like Node.JS, Angular.JS, Express.JS, and React.JS
- Learn Advanced HTML5 and CSS3 for building complex User Interfaces
- Learn Java Enterprise Edition for building enterprise-scale websites
- Learn how to design database and do SQL coding
- Hands-on Full-stack Web Development Bootcamp
- Learn Extensible Markup Language or XML programming
- Learn how to develop Native Android App Design with JavaScript React Native
- Move on to learn Native iOS App design with JavaScript React Native
Click here if you wish to learn more about training and career options available in the IT industry.
One-to-One Live Coding Classes
Coding Bootcamps school offers One-to-One Live Coding Classes for Beginners.