javascript - 是否可以在javascript函数中,从具有Google map 中位置的纬度和经度的var创建具有位置名称的var?

标签 javascript google-maps variables reverse-geocoding

我有以下简单的 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/

相关文章:

SwiftyJSON 如何正确访问变量?

python - 使用 Flask 在另一个函数中使用函数中的变量

javascript - 检查当前元素是偶数还是奇数

javascript - 我从 blender 导出到 three.js 的模型无法正确呈现

javascript - Javascript 初始化函数的外部化代码不起作用?

asp.net - 如何从服务器端 ASP.NET 2.0 获取 Google Map API 的距离

定义数组后,我可以通过用户输入在数组的括号/参数内定义变量吗?

javascript - 自动完成地址输入

javascript - 获取已更改的属性列表?

javascript - 如何在javascript上使用多个 "show on map"按钮获取正确的地址?