主题
反向地理编码
字数统计: 856 字
阅读时长: 约 2 分钟
当前版本: 4.29
了解如何使用地理编码服务查找某个位置附近的地址。
反向地理编码是将位置转换为地址或地点的过程。反向地理编码需要使用地理编码服务和反向编码 reverseGeocode
操作。输入一个初始位置,返回一个具有地名和位置等属性的地址。为了简化访问地理编码服务,可以使用 locator
模块。
在本教程中,使用 locator
进行反向地理编码,并在地图上查找最接近单击位置处的地址。
步骤
创建新 Pen
- 开始前,请完成显示地图教程。
添加模块
在
require
语句中,添加locator
模块。更多内容
GeoScene Maps SDK for JavaScript 提供有 AMD 模块和 ES 模块,但本教程基于 AMD。AMD
require
函数使用引用来确定加载哪些模块 - 例如,您可以指定"geoscene/Map"
来加载 Map 模块。加载模块后,它们将作为参数 (例如,Map
) 传递给回调函数,以便在应用程序中使用。保持模块引用和回调参数的顺序相同是很重要的。有关不同类型模块的更多信息,请访问工具指南主题。jsrequire([ "geoscene/config", "geoscene/Map", "geoscene/views/MapView", "geoscene/rest/locator" ], function (geosceneConfig, Map, MapView, locator) {
定义服务 url
使用 locator
模块访问地理编码服务和 reverseGeocode
操作。
定义一个变量
serviceUrl
,值为所引用的地理编码服务。jsconst view = new MapView({ container: "viewDiv", map: map, center: [-78.50169, -0.21489], zoom: 12 }); const serviceUrl = "https://www.geosceneonline.cn/server/rest/services/Utilities/GeocodingTools/GPServer";
反向地理编码
程序捕获地图上的点击位置,然后调用地理编码服务。如果找到地址,则服务返回该地址;如果未找到结果,则返回错误。在弹出窗口中使用纬度、经度和地址显示结果。
在主函数中,将
click
处理器添加至视图。创建params
并将location
设置为evt.mapPoint
。jsconst serviceUrl = "https://www.geosceneonline.cn/server/rest/services/Utilities/GeocodingTools/GPServer"; view.on("click", function (evt) { const params = { location: evt.mapPoint }; });
创建
showAddress
函数, 用来显示坐标和对应的地址。jsview.on("click", function (evt) { const params = { location: evt.mapPoint }; }); function showAddress(address, pt) { view.openPopup({ title: +Math.round(pt.longitude \* 100000) / 100000 + ", " + Math.round(pt.latitude \* 100000) / 100000, content: address, location: pt }); }
更新
click
处理程序,调用locationToAddress
,对mapPoint
进行反向地理编码。使用showAddress
函数显示结果的弹出窗口。jsview.on("click", function (evt) { const params = { location: evt.mapPoint }; locator.locationToAddress(serviceUrl, params).then( function (response) { // Show the address found const address = response.address; showAddress(address, evt.mapPoint); }, function (err) { // Show no address found showAddress("No address found.", evt.mapPoint); } ); });
运行应用程序
在 CodePen 中,运行代码以显示地图。
单击地图,对位置进行反向地理编码,返回具有最近地址的弹出窗口。
下一步是什么?
要了解如何使用其他API 功能,请参阅以下教程: