从地址中获取经纬度 c#

12

我正在使用地理编码器的web服务来获取地址、城市和州的纬度和经度。当我使用以下示例时,我没有得到纬度和经度信息。这里我做错了什么吗。

请求的地址:1125 E. 102nd Street, Los Angeles, CA

以下是我的代码:

private void GetLatLongFromAddress(string street, string city, string state)
{
    string geocoderUri = string.Format(@"http://rpc.geocoder.us/service/rest?address={0},{1},{2}", street, city, state);
    XmlDocument geocoderXmlDoc = new XmlDocument();
    geocoderXmlDoc.Load(geocoderUri);
    XmlNamespaceManager nsMgr = new XmlNamespaceManager(geocoderXmlDoc.NameTable);
    nsMgr.AddNamespace("geo", @"http://www.w3.org/2003/01/geo/wgs84_pos#");
    string sLong = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"//geo:long", nsMgr).InnerText;
    string sLat = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"//geo:lat", nsMgr).InnerText;

    Latitude = Double.Parse(sLat);
    Longitude = Double.Parse(sLong);
}

经纬度返回值为0,我已尝试添加邮政编码但未成功。是否有更好的Web服务可以提供最新的结果。

提前致谢。


谷歌地图可以实现这个功能。 - parapura rajkumar
1
这并不是一个关于C#的问题,而是一个关于Web服务的问题。 - A.R.
1
我尝试了你的代码 GetLatLongFromAddress("1125 E. 102nd Street", "Los Angeles", "CA"); 它返回了纬度为33.944015和经度为-118.255818。你是怎么调用这个方法的? - Raj Ranjhan
这个函数对我来说是有效的,返回了正确的值。也许问题出在你的经度和纬度对象上?当你逐步执行时,sLong和sLat的值是多少? - msmucker0527
现在它可以工作了。我在声明URI时漏掉了@符号。感谢大家验证代码。 - bladerunner
显示剩余4条评论
3个回答

5
我经常使用Bing Maps Rest APIs。您可以使用以下请求进行地理编码:
http://dev.virtualearth.net/REST/v1/Locations/CA/adminDistrict/postalCode/locality/addressLine?includeNeighborhood=includeNeighborhood&key=BingMapsKey

你可以在我写的关于响应式扩展的CodeProject文章中看到它的使用。
例如,你的地址:
http://dev.virtualearth.net/REST/v1/Locations/US/1125%20E.%20102nd%20Street,%20Los%20Angeles,%20CA?key=Ai9-KNy6Al-r_ueyLuLXFYB_GlPl-c-_iYtu16byW86qBx9uGbsdJpwvrP4ZUdgD

给出以下响应:
{
   "authenticationResultCode":"ValidCredentials",
   "brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
   "copyright":"Copyright © 2012 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
   "resourceSets":[
      {
         "estimatedTotal":1,
         "resources":[
            {
               "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
               "bbox":[
                  33.940492293415652,
                  -118.26180800227225,
                  33.948217728557005,
                  -118.24939194889963
               ],
               "name":"1125 E 102ND St, Los Angeles, CA 90002",
               "point":{
                  "type":"Point",
                  "coordinates":[
                     33.944355010986328,
                     -118.25559997558594
                  ]
               },
               "address":{
                  "addressLine":"1125 E 102ND St",
                  "adminDistrict":"CA",
                  "adminDistrict2":"Los Angeles Co.",
                  "countryRegion":"United States",
                  "formattedAddress":"1125 E 102ND St, Los Angeles, CA 90002",
                  "locality":"Los Angeles",
                  "postalCode":"90002"
               },
               "confidence":"High",
               "entityType":"Address",
               "geocodePoints":[
                  {
                     "type":"Point",
                     "coordinates":[
                        33.944355010986328,
                        -118.25559997558594
                     ],
                     "calculationMethod":"Parcel",
                     "usageTypes":[
                        "Display"
                     ]
                  },
                  {
                     "type":"Point",
                     "coordinates":[
                        33.944118499755859,
                        -118.25559997558594
                     ],
                     "calculationMethod":"Interpolation",
                     "usageTypes":[
                        "Route"
                     ]
                  }
               ],
               "matchCodes":[
                  "Good"
               ]
            }
         ]
      }
   ],
   "statusCode":200,
   "statusDescription":"OK",
   "traceId":"81518ba504a3494bb0b62bdb6aa4b291|LTSM002104|02.00.83.500|LTSMSNVM001473, LTSMSNVM001463, LTSMSNVM001452, LTSMSNVM001851, LTSMSNVM001458, LTSMSNVM001462"
}

或者...对于XML数据,添加o=xml:
http://dev.virtualearth.net/REST/v1/Locations/US/1125%20E.%20102nd%20Street,%20Los%20Angeles,%20CA?o=xml&key=Ai9-KNy6Al-r_ueyLuLXFYB_GlPl-c-_iYtu16byW86qBx9uGbsdJpwvrP4ZUdgD

这将给出:

<Response>
  <Copyright>Copyright ? 2012 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
  <BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
  <StatusCode>200</StatusCode>
  <StatusDescription>OK</StatusDescription>
  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
  <TraceId>b9af8a6b058b455ca9c368b9e32142fe|LTSM002102|02.00.83.500|LTSMSNVM002001, LTSMSNVM001464, LTSMSNVM001451, LTSMSNVM001452, LTSMSNVM001457, LTSMSNVM002052, LTSMSNVM001461</TraceId>
  <ResourceSets>
    <ResourceSet>
      <EstimatedTotal>1</EstimatedTotal>
      <Resources>
        <Location>
          <Name>1125 E 102ND St, Los Angeles, CA 90002</Name>
          <Point>
            <Latitude>33.944355010986328</Latitude>
            <Longitude>-118.25559997558594</Longitude>
          </Point>
          <BoundingBox>
            <SouthLatitude>33.940492293415652</SouthLatitude>
            <WestLongitude>-118.26180800227225</WestLongitude>
            <NorthLatitude>33.948217728557005</NorthLatitude>
            <EastLongitude>-118.24939194889963</EastLongitude>
          </BoundingBox>
          <EntityType>Address</EntityType>
          <Address>
            <AddressLine>1125 E 102ND St</AddressLine>
            <AdminDistrict>CA</AdminDistrict>
            <AdminDistrict2>Los Angeles Co.</AdminDistrict2>
            <CountryRegion>United States</CountryRegion>
            <FormattedAddress>1125 E 102ND St, Los Angeles, CA 90002</FormattedAddress>
            <Locality>Los Angeles</Locality>
            <PostalCode>90002</PostalCode>
          </Address>
          <Confidence>High</Confidence>
          <MatchCode>Good</MatchCode>
          <GeocodePoint>
            <Latitude>33.944355010986328</Latitude>
            <Longitude>-118.25559997558594</Longitude>
            <CalculationMethod>Parcel</CalculationMethod>
            <UsageType>Display</UsageType>
          </GeocodePoint>
          <GeocodePoint>
            <Latitude>33.944118499755859</Latitude>
            <Longitude>-118.25559997558594</Longitude>
            <CalculationMethod>Interpolation</CalculationMethod>
            <UsageType>Route</UsageType>
          </GeocodePoint>
        </Location>
      </Resources>
    </ResourceSet>
  </ResourceSets>
</Response>

因此,您提供的地址的纬度/经度为(33.9,-118.2)


2
Google Maps提供了一个Web服务API,返回经度/纬度信息,在主要国家使用效果良好。例如,请参见http://maps.google.com/maps/geo?q=1%205th%20ave,new%20york,ny,us。支持不同的输出格式,包括CSV、http://maps.google.com/maps/geo?q=1%205th%20ave,new%20york,ny,us&output=csv、JSON等。
我不熟悉geocoder.us,但是对于美国地址,Google地图绝对有效。
编辑1: 请参见http://code.google.com/apis/maps/faq.html#whatcountries以获取支持的国家列表。
编辑2: 为了更好的相关性,这里提供一个有关您所问地址的谷歌地图API调用示例:http://maps.google.com/maps/geo?q=1125%20E.%20102nd%20Street,%20Los%20Angeles,%20CA

@AnthonyBlake 我相信是某个特定的、任意大小或发展水平的国家。 - Andrew Barber
答案中添加了链接的国家 - Shan Plourde

2

通过地址获取经纬度 - Microsoft BingMapsRESTToolkit

微软有一个官方的BingMapsRESTToolkit,可以帮助您轻松地使用Bing Maps REST Services。为此,您需要安装BingMapsRESTToolkit NuGet Package

在这里,您可以使用GeocodeRequest按地址获取位置。您可以通过将Query属性设置为指定的地址或将Address属性设置为AddressSimpleAddress的实例来指定地址。

例子:

var request = new GeocodeRequest();
request.BingMapsKey = "Your Map Key";

request.Query = "The Postal address";

//OR
//request.Address = new SimpleAddress()
//{
//    CountryRegion = "The Country",
//    AddressLine = "The official street line of an address relative to the area",
//    AdminDistrict = "The subdivision name in the country or region for an address",
//    Locality = "The locality, such as the city or neighborhood", 
//    PostalCode = "The postal code",
//};

var result = await request.Execute();
if (result.StatusCode == 200)
{
    var toolkitLocation = (result?.ResourceSets?.FirstOrDefault())
        ?.Resources?.FirstOrDefault() as BingMapsRESTToolkit.Location;
    var latitude = toolkitLocation.Point.Coordinates[0];
    var longitude = toolkitLocation.Point.Coordinates[1];

    // Use latitude and longitude
}

更多信息:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接