使用地理位置和谷歌地图获取位置的地址

时间:2018-01-02 03:20:36

标签: javascript jquery html google-maps

我的网页上有一个表单,可以在表单字段中获取用户的地址。

当用户在位置提示上单击“允许”时,我的目的是在表单的输入框中获取用户的地址。

提示出现,但此代码无法获取用户的地址。

我正在寻找像this

这样的东西

这是我的代码

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);
        }
    });
}
});

3 个答案:

答案 0 :(得分:0)

要开始使用Google Maps API,您需要将Google Maps JS文件包含在脚本中。

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

您需要使用自己的密钥替换YOUR_API_KEY。您需要为您的应用程序生成一个。 Get API Key

您的代码中存在另一个问题。

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

id="address"元素是输入字段,因此.html()函数不可用。您需要使用.val()功能。所以你可以用下面的那一行代替那一行。

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

这应该可以让你的代码正常工作。

答案 1 :(得分:0)

您的文本字段未填充地址的原因是代码中的这一行:

在“getCurrentAddress”函数中: $("#address").html(results[0].formatted_address);

问题在于,此行是您要设置输入“textfield”。在这种情况下,你不能做.html()

您可以通过将其更改为: $("#address").val(results[0].formatted_address);

看看以下小提琴: https://jsfiddle.net/ezr6z7so/

答案 2 :(得分:0)

试试这个 -

 <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>

网址http://maps.googleapis.com/maps/api/geocode/json?latlng=22.3545947,91.8128751&sensor=true以JSON格式返回地址信息。你想要&#34; formatted_address&#34; &#34;结果&#34;中的0索引JSON的索引。 有关更多信息,请参阅JSON文件。