Reputation: 28783
I have the following code on a page where users can create posts:
<script>
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
$('input#latitude').val(position.coords.latitude);
$('input#longitude').val(position.coords.longitude);
}
getLocation();
</script>
This populates two hidden fields on a form with the users coordinates. These coordinates are saved in a database table for the post so that the post can be shown on a map so other users can see where it was posted.
However if a user decides to: A) not share their location B) uses a browser that doesn't support geolocation
I won't be able to save this information and it will defeat the point of the application!
Is their a better way to do this? And someway of handling the issues with when a user decides not to share their location or doesn't have geolocation?
So far I have: http://dev.driz.co.uk/location/ as a test, and I also have field that will be populated with the users location in the form of a town/city. This is so that the user can see where they are currently posting from and if it's wrong then it'll allow them to change it and update the coordinates (note that this will just get the central location rather than there ACTUAL location as we'll only be searching for the town they enter).
I'm looking to use the Google Maps API to work out the users location.
To clarify what I want to build:
1.) The users location coming from the users table will populate the field shown on the page. This will then be overridden with their current location using Geolocation. If they don't have this or block it, then it will just use the pre filled text.
2.) Using either this location value or geolocation, we will get the coordinates for the user and then insert them into the hidden fields.
3.) If the user decides that the location is wrong OR they want to change it to somewhere else for whatever reason, then they can type it in the box and click the change button which will then find the coordinates for that location. (show error if it can't be found and use the prefilled defaults from the user location until a new is found).
Can anyone help out? Thanks
Upvotes: 2
Views: 3695
Reputation: 5287
I've had some success with http://ipinfodb.com/ for cases where the user doesn't accept or their browser doesn't support geolocation. They provide a lot of sample code for various languages, including accessing the API directly using javascript, and I've found the restrictions and accuracy of their free API to be reasonable enough for sites with light to moderate traffic.
Upvotes: 0
Reputation: 516
Do you want to do that only in browser? If not and user decides to not to share his location you can estimate coordinates in backend using GeoIP library and geocoding service in Google Maps API.
Upvotes: 1