介绍
esri-leaflet-geocoder
是一个基于 Leaflet 和 ArcGIS API for JavaScript 的 npm 包,用于在 Leaflet 应用程序中实现地理编码和反向地理编码功能。它可以帮助开发者更加便捷地实现地址搜索和标记等功能。
安装
通过 npm 可以很容易地安装 esri-leaflet-geocoder
:
npm install esri-leaflet-geocoder
使用方法
地理编码
在 Leaflet 应用程序中实现地理编码,可以使用 L.esri.Geocoding.geocodeService()
方法创建一个地理编码服务,并指定服务的 URL:
var geocodeService = L.esri.Geocoding.geocodeService({ url: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer' });
然后,在需要进行地理编码的位置调用 geocode()
方法即可:
geocodeService.geocode().text('1600 Pennsylvania Ave NW, Washington, DC').run(function (error, response) { if (error) { console.log(error); } else { console.log(response.results[0].latlng); } });
上面的代码将会输出该地址对应的经纬度。
反向地理编码
反向地理编码是将经纬度转换为地址的过程。在 Leaflet 应用程序中实现反向地理编码,可以使用 L.esri.Geocoding.reverseGeocode()
方法:
-- -------------------- ---- ------- --- -------------- - --------------------------------- ---- --------------------------------------------------------------------- --- --- ------ - ----------------- ---------- ---------------------------------------------------- ------- ------- - -- ------- - ------------------- - ---- - --------------------------------------- - ---展开代码
上面的代码将会输出该经纬度对应的地址。
示例代码
地理编码
-- -------------------- ---- ------- --------- ----- ------ ------ -------------- --------- ------------ ----- ---------------- ------------------------------------------------------- ----------------------------------------------------------------------------------- --------------- ------- ----------------------------------------------------- ----------------------------------------------------------------------------------- ------------------------ ------- --------------------------------------------------------------- ----------------------------------------------------------------------------------- ------------------------ ------- --------------------------------------------------------------------------------- ----------------------------------------------------------------------------------- ------------------------ ------- ------ ---- -------- -------------- -------------- -------- --- --- - ------------------------------ ---------- ---- ---------------------------- - ----------------------------------------------------------- -------- ----------------------------------------------------------------------------------展开代码