是否可以在 javascript 函数中,从具有 Google 地图中位置的纬度和经度的 var 创建带有位置名称的变量



我有以下简单的javascript函数:

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

有没有办法在这个脚本上创建一个变量,该变量接受location_coordinates并将在另一个变量中返回该位置的位置名称?

你通常需要某种地理编码服务(谷歌!(,如谷歌,Mapquest等等。您特别要寻找的是"反向地理编码"!对于这些服务,您通常需要一个帐户,您可以在其中创建一个应用程序,该应用程序将为您提供要使用的 API 密钥,有些人很好,可以将一些留在 Web 中 =(,因此以下是使用 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>

最新更新