Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Geolocation and Interactive Maps

DZone's Guide to

Geolocation and Interactive Maps

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Geolocation feature in a web browser is the key to improve the location-awareness of a web app. The following simple geolocation demo combines the information given by the browser with a textual geocoded address and a visual marker in a map.

geomaps

Getting the approximate address is not difficult to achieved using Google Maps Reverse Geocoding API. In fact, this was exactly how I have done it in my previous geolocation example. Now, displaying the location itself is also not a difficult matter, one can simple use the ubiquitous Google Maps or the alternatives such as OpenStreetMap.

With the recent release of Leaflet 0.6, I finally found some extra motivation to show how to use it in this context. For the tile data itself, I decided to give CloudMade a try (you need to sign up to get the API key and enjoy 500,000 free tiles every month). It took only a few minutes to implement this feature, combining Leaflet and CloudMade, especially if you follow Leaflet’s Getting Started guide. Some relevant code fragment:

map = L.map('map').setView([coords.latitude, coords.longitude], 11);
map.zoomControl.setPosition('bottomright');
L.tileLayer('http://{s}.tile.cloudmade.com/apikey/997/256/{z}/{x}/{y}.png', {
  attribution: 'Map data © ...', maxZoom: 18
}).addTo(map);
geocoder.geocode({'latLng': pos}, function (results, status) {
  var addr;
  if (status == google.maps.GeocoderStatus.OK) {
    addr = results[0].formatted_address;
    geocode.textContent = addr;
    L.marker([coords.latitude, coords.longitude]).addTo(map).bindPopup(addr);
});

Using Leaftlet, the map also works well on a variety of mobile platforms, everything from Android smartphones to Chromebook Pixel. And yes, it understands touch API for smooth panning and zooming. It feels good when pinch-to-zoom just works!

To give it a try, hit ariya.github.io/html/geolocation with your modern browser.



Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Ariya Hidayat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}