首页 > 解决方案 > 是否可以在 javascript 函数中从 var 中创建具有纬度和经度的 Google 地图中具有位置名称的 var?

问题描述

我有以下简单的javascript函数:

<script>
var location_coordinates = "37.652007,25.030289";
document.write (location_coordinates);
</script>

有什么方法可以在此脚本上创建一个变量,该变量location_coordinates将在另一个变量中返回该位置的位置名称?

标签: javascriptgoogle-mapsvariablesreverse-geocoding

解决方案


您通常需要某种地理编码服务(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>


推荐阅读