mysterykid
mysterykid

Reputation: 133

Add a user inputted location to OpenStreetMap using Leaflet.js

I am trying to create a map of user-inputted locations, however to do this I need to convert inputted cities into their latitude and longitude. This allows me to easily plot them using Leaflet.js using L.marker(point).addTo(map)

Given the input of say "London" is there a way using the OpenStreetMap API to fetch these values? here are very few API tools available that will do this task (from my research) without the need for an API key.

I want to avoid using the google maps API if possible and would appreciate any help, whether it be API recommendations or OpenStreetMap ideas, as I am relatively new to javascript.

Thanks in advance!

Upvotes: 0

Views: 679

Answers (1)

mysterykid
mysterykid

Reputation: 133

As recommended in the comments, the solution was to use nomination, in particular, their search queries.

I ended up using jQuery's getJson function to fetch the data from the API as follows.

$(function () {
  geocoding = function (city, country) {
    var url = `https://nominatim.openstreetmap.org/search?city=${city}&country=${country}&format=json`
    $.getJSON(url, function (data) {
      //data is the JSON string
      lat = data[0].lat
      lon = data[0].lon
      ...
    });
  }
})

Upvotes: 0

Related Questions