我有以下简单的 JavaScript 函数:
<script>
var location_coordinates = "37.652007,25.030289";
document.write (location_coordinates);
</script>
有什么方法可以在此脚本上创建一个变量,该变量采用 location_coordinates
并将在另一个变量中返回该位置的位置名称?
最佳答案
您通常需要某种地理编码服务(Google!),例如 Google、Mapquest 等等。您特别要寻找的是“反向地理编码”!对于这些服务,您通常需要一个帐户,您可以在其中创建一个应用程序,该应用程序将为您提供一个可供使用的 API key ,有些人很友善地将一些 key 留在网络中 =),所以这里是使用地理编码的坐标示例服务来自MapQuest :
btn.addEventListener('click', function(e) {
// fetch the address
fetch(`https://open.mapquestapi.com/geocoding/v1/reverse?key=jzZATD7kJkfHQOIAXr2Gu0iG62EqMkRO&location=${lat.value},${lng.value}`)
.then((data) => {
return data.json();
})
.then((json) => {
// here you can do something with your data
// like outputting the address you received
// from the Geocoding Service of your choice
if ( json.results[0] ) {
const result = json.results[0].locations[0];
output.innerHTML = `
<p>The address for your coordinates is:</p>
<address>
<span class="street" style="display: block">${result.street}</span>
<span class="postalcode">${result.postalCode}</span>
<span class="city">${result.adminArea5}</span>
<b class="country" style="display: block">${result.adminArea3}</b>
</address>
`;
}
})
.catch((err) => {
console.log(err);
});
});
<input type="text" placeholder="Latitude" id="lat" value="37.652007" />
<input type="text" placeholder="Longitude" id="lng" value="25.030289" />
<button type="button" id="btn">Get Address</button>
<div id="output" style="width: 300px; background: lightgray; padding: 24px; margin-top: 12px;"></div>
关于javascript - 是否可以在javascript函数中,从具有Google map 中位置的纬度和经度的var创建具有位置名称的var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56694352/