GeoLocation Zip Code

34,189

Solution 1

Try position.address.postalCode

See the following demo i made to see what is supported by your browser/device

https://jsfiddle.net/gaby/Sx5cj/

Solution 2

Looking at the latest HTML5 Geolocation API, i do not see the support for position.address.city, position.address.region or position.address.city yet. So, i'd have to say that is not currently supported.


Update:

Address look up seems to be supported in firefox per @Gaby aka G. Petrioli answer

Solution 3

There is no support for address in HTML 5 Geolocation API, but you can achieve this combining it with Google Maps API: here is an example getting the zipCode but you can use it to get the entire address:

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        var point = new google.maps.LatLng(lat, long);
        new google.maps.Geocoder().geocode(
            {'latLng': point},
            function (res, status) {
                var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
                $("#location").val(zip);          
            }
        );
    });
}
Share:
34,189
pertrai1
Author by

pertrai1

Updated on September 22, 2020

Comments

  • pertrai1
    pertrai1 over 3 years

    I am using the following code for getting location and city, but can't get it to give me the zip code if the person gives me permission. Please let me know if this is possible to do with this code. All it is doing is populating a text field if given permission to access.

    <script type="text/javascript">
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
         $("#location").val(position.address.city+", "+position.address.region);
      });
     }
    

  • Hash Borgir
    Hash Borgir about 7 years
    $("#location").val(zip); should be $("#location").val(zip[1]); otherwise it would return the entire array's contents.
  • Azimuth
    Azimuth almost 6 years
    (index):78 [Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS in console.
  • Gabriele Petrioli
    Gabriele Petrioli almost 6 years
    @Azimuth just use the https:// version of jsfiddle. Have updated the answer as well.
  • Azimuth
    Azimuth almost 6 years
    Doesn't work in Chrome. position.address is undefined.
  • Kevin Danikowski
    Kevin Danikowski almost 5 years
    Not bad idea, but is google api built into modern browsers?
  • Maddocks
    Maddocks over 4 years
    @KevinDanikowski NO, you include google maps api as a CDN <script src=.. > in your app