These days with web apps being run on tablets and smartphones, location-awareness is becoming of a preferable feature to have. Instead of an app asking the user to enter his location, the app finds it on its own.
The most reliable way of finding a user’s location in terms of latitude/longitude was using the Google Geolocation API, which was part of Google Gears. which unfortunately has been discontinued some months back.
However, geolocation still works if you are using Google Maps. And again it is NOT necessary to have to display a google map just because you want to do a geolocation call.
We are just using Google Maps to use its geolocation features.
The sample javascript is below:
<script src="http://maps.google.com/maps/api/js?sensor=false"> </script> <script type="text/javascript"> function doLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position){ var latitude = position.coords.latitude; var longitude = position.coords.longitude; var fld = document.getElementById("address"); if (fld) { fld.value = "(" + latitude + "," + longitude + ")"; } var coords = new google.maps.LatLng(latitude, longitude); var mapOptions = { zoom: 15, center: coords, mapTypeControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map( document.getElementById("mp"), mapOptions ); var marker = new google.maps.Marker({ position: coords, map: map, title: "Your current location!" }); }); }else { alert("Geolocation API is not supported in your browser."); } } </script>
The front end script shown below:
<style type="text/css"> #mp { height: 0px; width: 0px; } </style> <div id="mp"></div>
- In the javascript function, it is assumed there is a textbox called ‘address’, which will be assigned the lat/long value obtained from the geolocation call. Once you have the coordinates, you can assign it to anything you want.
- The div which will hold the google map has been given a width and height of zero, so it does not show. If you need a map then you can give it height and width and position.
- The function doLocation can be called at page load or on some click event in the page.
What I’m curious about is saving a location like what Craigslist does. For instance, if you click “New York” and pick a city, it will remember in your browser what city that was for the next time you log onto the site. I’m very curious how to do this and cannot find any material. What you have here is great and I may even use this for my new site, but I am still curious how to achieve this effect.
Jon,
Storing a user’s preference can be done via cookies. Once you have a user’s location confirmed, write it into the site cookie. This gets stored in the user’s browser.
You need some server-side code on the page which first checks for the cookie and if any location is already saved in it. If it is then you can read it and do what you need to do with it.