gpt4 book ai didi

javascript - 使用 geo.js 进行地理定位

转载 作者:行者123 更新时间:2023-12-02 19:36:38 25 4
gpt4 key购买 nike

我需要在我的网站中使用地理定位作为横幅。我发现this library这似乎不错:

在我的页面中,我添加了此代码,浏览器向我显示允许获取位置的警报。

代码:

<script type="text/javascript">
if(geo_position_js.init()){
geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
}
else{
alert("Functionality not available");
}

function success_callback(p)
{

var latitudine = +p.coords.latitude.toFixed(2);
var longitudine = p.coords.longitude.toFixed(2);

alert(latitudine+' - '+longitudine);
}

function error_callback(p)
{
alert('error='+p.message);
}

</script>

我可以毫无问题地看到警报,但我需要让城市加载不同的横幅。我怎样才能做到这一点?

我还找到了这项服务:findNearbyPlaceName

它允许从纬度和经度查找国家/地区等,但我如何使用这些信息?我看到他们有一个带有 xml 或 json 的回调,我尝试使用此代码获取 url,但这是错误的,因为浏览器不显示警报:

<script type="text/javascript">
if(geo_position_js.init()){
geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
}
else{
alert("Functionality not available");
}

function success_callback(p)
{

var latitudine = +p.coords.latitude.toFixed(2);
var longitudine = p.coords.longitude.toFixed(2);

$.getJSON(
'http://http://api.geonames.org/findNearbyPlaceNameJSON?lat='+latitudine+'&lng='+longitudine,
function(data) {
alert(data);
}
);

}

function error_callback(p)
{
alert('error='+p.message);
}

</script>

最佳答案

您需要的是“反向地理编码器”。

使用反向地理编码器,您可以获得特定坐标的城市名称(甚至街道名称)。

一种非常简单的方法是使用 Google Maps API V2 和 V3 中提供的 Google 地理编码器:

  var geocoder;

function codeLatLng(latitude, longitude) {
var
geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(latitude, longitude);

geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
// results[1].formatted_address contains the city name
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}

示例(来源):https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding

希望这有帮助!

关于javascript - 使用 geo.js 进行地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com