知识库

使用 Arcgis 进行地理编码

先决条件

  • 创建/获取 ArcGIS 账户。

  • 在你的账户中创建应用程序。该应用程序将分配一个 ‘client_id’ 和 ‘secret’。

APOC

The APOC library provides a apoc.spatial.geocode('address') procedure (as well as reverseGeocode), that supports geocoding against OpenStreetMap and Google Maps. It also supports other providers (ex: opencage) with a more explicit configuration of the API call (in neo4j.conf)

apoc.spatial.geocode.provider=opencage
apoc.spatial.geocode.opencage.key=<api_key>
apoc.spatial.geocode.opencage.url=http://api.opencagedata.com/geocode/v1/json?q=PLACE&key=KEY
apoc.spatial.geocode.opencage.reverse.url=http://api.opencagedata.com/geocode/v1/json?q=LAT+LNG&key=KEY

其中 KEY 会被 API 密钥替换,PLACE 会在运行时被替换为需要地理编码的地址(相应地 LAT/LNG 为需要逆向地理编码的坐标)。

对于 ArcGIS,密钥应为应用程序令牌,URL 如下(这是公共 ArcGIS API 端点): apoc.spatial.geocode.arcgis.url=https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&outFields=Match_addr,Addr_typ&singleLine=PLACE&token=KEY

不幸的是,apoc 过程期望提供者返回的 JSON 响应中包含一个名为 “results” 的列表。但 ArcGIS API 端点并非如此。

  • 端点 ‘findAddressCandidates’ 返回一个 “candidates” 列表

  • 另一个批量地理编码端点 ‘geocodeAddresses’ 返回一个 “locations” 列表

因此 apoc.spatial 过程在这里无法使用。

使用 apoc.load.json 的变通方法

apoc.load.json 过程允许你调用任何 HTTP/REST API 并直接在 cypher 中处理响应。

你可以使用 apoc.static 过程从 neo4j.conf 中读取 API 密钥和 URL,方式与 apoc.spatial.geocode 类似。以下两个属性是进行地理编码所必需的(这里使用公共的 ArcGIS 服务器;如果需要,请换成你自己的 ArcGIS 服务器主机名)

apoc.static.arcgis.key=<arcgis_token>
apoc.static.arcgis.geocode_url=https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&outFields=Match_addr,Addr_typ&singleLine=

然后运行以下 cypher 查询

WITH 'Statue of Liberty, Liberty Island New York, NY 10004' as address
// get the configuration properties
CALL apoc.static.getAll("arcgis") yield value AS arcgis
// build the URL
WITH arcgis.geocode_url+apoc.text.urlencode(address)+'&token='+ arcgis.key as url
// extract the top result
CALL apoc.load.json(url, '$.candidates[0].location') YIELD value as location
return location.x, location.y

临时令牌

ArcGIS 应用程序令牌可能是临时的(默认 2 小时)。这意味着你可能无法在 neo4j.conf 中硬编码令牌。要获取新令牌,需要使用你的应用程序凭证调用 Authentication API。你可以再次使用 apoc.load.json 在 cypher 中完成此操作。

在 neo4j.conf 中,添加令牌 API 调用的构件

apoc.static.arcgis.client_id=<application_client_id>
apoc.static.arcgis.client_secret=<secret>
apoc.static.arcgis.token_url=https://www.arcgis.com/sharing/rest/oauth2/token?grant_type=client_credentials

然后运行以下 cypher 查询

CALL apoc.static.getAll("arcgis") yield value AS arcgis
WITH arcgis.token_url+'&client_id='+arcgis.client_id+'&client_secret='+arcgis.client_secret as tokenUrl
CALL apoc.load.json(tokenUrl) YIELD value as tokenResponse
WITH tokenResponse.access_token as token
// proceed with geocoding using 'token'
© . This site is unofficial and not affiliated with Neo4j, Inc.