0

I have the following simple javascript function:

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

Is there any way, to create on this script a variable that takes location_coordinates and will returns in another variable the location name of this position?

1 Answers1

1

You usually need some kind of Geocoding Service (Google that!) like Google, Mapquest and many more out there. What you specifically are looking for is "Reverse Geocoding"! For these services you usually need an account where you create an app which will give you an API key to use, some people are nice enough to leave some out there in the web =), so here is an example for your coordinates using the Geocoding Service from 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>
exside
  • 2,730
  • 1
  • 10
  • 16
  • Is it a way in order to get all these information without button clicking? I have a variable that dynamically will give latitude and longitude information and i want if is it possible to have another variable that will have as result address name and so on. That's above is a very useful code for me but may something little have to change... – Loukas Triantafyllopoulos Jun 20 '19 at 23:16
  • of course, you just execute the `fetch()` part without an `EventListener` around it – exside Jun 20 '19 at 23:17