javascript中的反向地理编码代码

时间:2014-07-21 02:19:03

标签: javascript reverse-geocoding

当我运行此代码时,我有一个经度和纬度,我想修改此代码,所以当它运行而不是经度和纬度时,我得到一个街道地址。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geolocation</title>
</head>
<body>
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
<script>
    function geoFindMe() {
    var output = document.getElementById("out");

    if (!navigator.geolocation){
      output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
      return;
}

function success(position) {
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;

output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude +      '°</p>';

var img = new Image();
img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," +    longitude + "&zoom=13&size=300x300&sensor=false";

output.appendChild(img);

};

  function error() {
     output.innerHTML = "Unable to retrieve your location";
    };

     output.innerHTML = "<p>Locating…</p>";

    navigator.geolocation.getCurrentPosition(success, error);
}
  </script>
  `enter code here`</body>
  </html>

1 个答案:

答案 0 :(得分:0)

请试试这个

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Geolocation</title>
</head>
<body>

<p id="geoLocationText">Click the button for reverse geolocation:</p>

<button onclick="getLocation()">Show my location</button>
<div id="mapholder"></div>

<input id="latlng" type="text" value="40.714224,-73.961452">
<input type="button" value="Reverse Geocode" onclick="codeLatLng()">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var x = document.getElementById("geoLocationText");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, showError, options);
        console.log('searching');
        x.innerHTML = "Searching";
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
   }
}

var options = {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0
};

function success(pos) {
    var crd = pos.coords;

    console.log('Your current position is:');
    console.log('Latitude : ' + crd.latitude);
    console.log('Longitude: ' + crd.longitude);
    console.log('More or less ' + crd.accuracy + ' meters.');

    var latlon = crd.latitude+","+crd.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&zoom=14&size=400x300&sensor=false";

    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
};

function error(err) {
    console.warn('ERROR(' + err.code + '): ' + err.message);
};

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            console.warn('ERROR(' + error.code + '): ' + error.message);
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            console.warn('ERROR(' + error.code + '): ' + error.message);
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            console.warn('ERROR(' + error.code + '): ' + error.message);
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            console.warn('ERROR(' + error.code + '): ' + error.message);
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

function codeLatLng() {
    var geocoder = new google.maps.Geocoder();

    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);

    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                x.innerHTML = results[1].formatted_address;
                console.log(results[1].formatted_address);
                var latlon = lat+","+lng;
                var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
                +latlon+"&zoom=14&size=400x300&sensor=false";

                document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}
</script>

</body>
</html>

请尝试将结果[1]更改为以下任何一项,不同的数据会在formatted_address中提供更多或更少的内容

results[0].formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
results[1].formatted_address: "Williamsburg, NY, USA",
results[2].formatted_address: "New York 11211, USA",
results[3].formatted_address: "Kings, New York, USA",
results[4].formatted_address: "Brooklyn, New York, USA",
results[5].formatted_address: "New York, New York, USA",
results[6].formatted_address: "New York, USA",
results[7].formatted_address: "United States"