-1

There's a form on my webpage which is supposed to get the address of the user in a formfield.

When the user clicks allow on the location prompt my purpose is to get the address of the user in an input box in the form.

The prompt comes but this code is unable to fetch the address of the user.

I am looking for something like this

Here's my code

HTML

<form id="contact" action="" method="post" align="center">

<fieldset>
  <input placeholder="Your Address" id="address" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
  <button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>

Javascript

<script src="https://code.jquery.com/jquery-1.10.1.js"></script>
<script>
$(document).ready(function () {

var currgeocoder;

//Set geo location lat and long
navigator.geolocation.getCurrentPosition(function (position, html5Error) {
    geo_loc = processGeolocationResult(position);
    currLatLong = geo_loc.split(",");
    initializeCurrent(currLatLong[0], currLatLong[1]);
});

//Get geo location result
function processGeolocationResult(position) {
    html5Lat = position.coords.latitude; //Get latitude
    html5Lon = position.coords.longitude; //Get longitude
    html5TimeStamp = position.timestamp; //Get timestamp
    html5Accuracy = position.coords.accuracy; //Get accuracy in meters
    return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}

//Check value is present or
function initializeCurrent(latcurr, longcurr) {
    currgeocoder = new google.maps.Geocoder();

    console.log(latcurr + "-- ######## --" + longcurr);

    if (latcurr != '' && longcurr != '') {
        //call google api function
        var myLatlng = new google.maps.LatLng(latcurr, longcurr);
        return getCurrentAddress(myLatlng);
    }
}

//Get current address
function getCurrentAddress(location) {
    currgeocoder.geocode({
        'location': location
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results[0]);
            $("#address").html(results[0].formatted_address);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}
});

Prakhar Sood
  • 53
  • 1
  • 8

3 Answers3

1

Try this-

 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
        <script type="text/javascript">
           $(document).ready(function(){

            function getGeoLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                } else {
                    document.getElementById("address").value = "Geolocation is not supported by this browser.";
                }
            }

            function showPosition(position) {
                var lat = position.coords.latitude;
                var lang = position.coords.longitude;
                var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lang + "&sensor=true";

                $.getJSON(url, function (data) {
                        var address = data.results[0].formatted_address;
                        document.getElementById("address").value = address;

                });
            }               
});    
        </script>

The url http://maps.googleapis.com/maps/api/geocode/json?latlng=22.3545947,91.8128751&sensor=true returns address information in JSON format. You want the "formatted_address" of 0 index inside the "result" index of the JSON. See the JSON file for more information.

Hq Shiblu
  • 91
  • 5
0

In order to start using Google Maps API, you need to include the Google Maps JS file into your script.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

You need to replace YOUR_API_KEY with your own key. You need to generate one for your application. Get API Key

There is another issue in your code at this line.

$("#address").html(results[0].formatted_address);

The element with id="address" is an input field, so the .html() function is not available on it. You need to use the .val() function. So you can replace that line with the one below.

$("#address").val(results[0].formatted_address);

This should get your code working.

Vivek
  • 2,665
  • 1
  • 18
  • 20
0

The reason your textfield is not being populated with the address is because of this line in your code:

In "getCurrentAddress" function: $("#address").html(results[0].formatted_address);

The problem, in this line is that you want to set an input "textfield". In this case you cannot do .html()

You can fix this by changing it to: $("#address").val(results[0].formatted_address);

Take a look at the following fiddle: https://jsfiddle.net/ezr6z7so/

techbum
  • 61
  • 1
  • 7