$(document).ready(function(){
$("#getLocation").on("click", function(){
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
$('#city').html(location.city);
});
});
});
这是我一直在使用的当前JavaScript,而here是我使用它的CodePen的链接。我使用用户城市的位置来查找该城市的天气。
我已经在多个网站上阅读了有关如何使用多个不同的API来获取用户城市位置的信息,但是我的项目中没有使用过。感谢您的帮助,提前。
答案 0 :(得分:2)
要详细说明我以前的答案,更清晰,更香草的JavaScript方式来获取坐标就像这样。
这只是一些短线,其好处是巨大的:
请参阅下面的图片了解结果。超轻量快速。有关更多详细信息,请查看MDN - Using Geolocation。
if ("geolocation" in navigator) {
// Do something with coordinates returned
function processCoords(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let first_div = document.querySelector('div');
let el_h2 = document.createElement('h2');
// Set h2 text as coordinates
el_h2.innerText = `Latitude: ${latitude}, Longitude: ${longitude}`;
// Append h2 to document
first_div.appendChild(el_h2);
}
// Fetch Coordinates
navigator.geolocation.getCurrentPosition(processCoords);
}
获取城市:
通常最佳做法是仅在数据库中存储坐标 然后在需要时提出单独的城市请求。这会让事情发生 当您想要实现在移动设备或桌面上说地图视图时更容易 所有都使用坐标而不是地块的名称。
您可以使用Google Maps API直接传递LatLong数据。有人提出了如何做到这一点的要点here。
使用GMaps代替Geo-IP的好处: