javascript - 是否可以在 javascript 函数中从 var 中创建具有纬度和经度的 Google 地图中具有位置名称的 var?
问题描述
我有以下简单的javascript函数:
<script>
var location_coordinates = "37.652007,25.030289";
document.write (location_coordinates);
</script>
有什么方法可以在此脚本上创建一个变量,该变量location_coordinates
将在另一个变量中返回该位置的位置名称?
解决方案
您通常需要某种地理编码服务(Google that!),例如 Google、Mapquest 等等。您特别要寻找的是“反向地理编码”!对于这些服务,您通常需要一个帐户,您可以在其中创建一个应用程序,该应用程序将为您提供一个 API 密钥供您使用,有些人很乐意在网络上留下一些 =),所以这里是一个使用地理编码的坐标示例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>
推荐阅读
- c++ - 如何使用 ifstream 获取文件中的最新更改?
- r - 平均R中的不同列
- sql - SQL:您如何计算设施的占用率/使用中的数量?
- arrays - 为什么我不能迭代在 C 中返回的字符串?
- javascript - 如何将 Ajax 请求发送到同一服务器的不同 url
- java - 如何在android studio中保存seekbar值?
- opencv - 如何修复 gocv 上的 GLCM 调用
- linq - 无法使用 marten 和 Linq 查询子类型
- google-chrome - 编写用于触发 chrome 快捷方式的 Chrome 扩展程序
- python - 循环遍历列名称熊猫的错误