描述

反向地理编码确定地图上给出点的地址。本例展示了如何通过ArcGIS JavaScript API做反向地理编码。

反向地理编码和常规的地理编码请求都使用Locator类和ArcGIS Server geocode service。 调用locationToAddress方法(和常规的地理编码相反addressToLocations)进行反向地理编码。下面的监听器捕获鼠标单击事件并为单击的点调用locationToAddress方法:

dojo.connect(map, "onClick", function(evt) {
  map.graphics.clear();
  locator.locationToAddress(evt.mapPoint, 100);
});

onLocationToAddressComplete事件的监听器传递最好的AddressCandidate给一个回调函数。然后回调函数结合候选的点和图形并增加到地图里。函数也使用InfoTemplate格式化一个单击图形显示的InfoWindow。注意为了定位信息窗口,地址结果的地图点必须被转换为一个屏幕点。

var screenPnt = map.toScreen(candidate.location);
map.infoWindow.show(screenPnt,map.getInfoWindowAnchor(screenPnt));

为了保持信息窗口总是可见的,信息窗口位于锚点所在的四分之一地图的相反方向。例如,如果点位于地图右上角,信息窗口显示在点的左下方。

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>Find Address</title>
<link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.5/js/dojo/dijit/themes/tundra/tundra.css">
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.5"></script>
<script type="text/javascript">
dojo.require("esri.map");
dojo.require("esri.tasks.locator"); function init() { //创建地图并添加
var map = new esri.Map("map",{ extent: new esri.geometry.Extent(-95.2991, 38.9379, -95.2476, 38.963, new esri.SpatialReference({wkid:4326}))});
var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer");
map.addLayer(tiledMapServiceLayer); var locator = new esri.tasks.Locator("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Locators/ESRI_Geocode_USA/GeocodeServer"); //设置显示窗口的格式
var infoTemplate = new esri.InfoTemplate("Location","Street: ${Address}<br />City: ${City}<br />State:${State}<br />Zip:${Zip}");
//设置样式:圆,实心,蓝色
var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,255]),2), new dojo.Color([0,0,255]));
//
dojo.connect(locator,"onLocationToAddressComplete",function(candidate) {//事件的监听器
if (candidate.address) {
var graphic = new esri.Graphic(candidate.location, symbol, candidate.address, infoTemplate);
map.graphics.add(graphic);
map.infoWindow.setTitle(graphic.getTitle());
map.infoWindow.setContent(graphic.getContent());
var screenPnt = map.toScreen(candidate.location);
map.infoWindow.show(screenPnt,map.getInfoWindowAnchor(screenPnt));
} }); dojo.connect(map, "onClick", function(evt) {
map.graphics.clear();
locator.locationToAddress(evt.mapPoint, 100);
});
}
dojo.addOnLoad(init);
</script>
</head>
<body class="tundra">
Left click on the map to get address.
<div id="map" style="width:1200px; height:600px; border:1px solid #000;"></div>
</body>
</html>
05-11 19:20