简体   繁体   中英

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!

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
      ...
    });
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM