简体   繁体   English

从地址 C# 获取纬度经度

[英]Get Latitude Longitude from an address c#

I am using a webservice from geocoder to get the lat and long from address, city and state.我正在使用地理编码器的网络服务来获取地址、城市和州的经纬度。 When I use the example below, i don't get the lat and long.当我使用下面的示例时,我没有得到经纬度。 Am I doing something wrong here.我在这里做错了什么。

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

Here is my code:这是我的代码:

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);
}

The lat and long comes back with 0. I tried to add zip code too but that didn't work. lat 和 long 返回 0。我也尝试添加邮政编码,但这没有用。 Is there any better webservices that would give me the up to date results.有没有更好的网络服务可以给我最新的结果。

Thanks in advance.提前致谢。

I often use the Bing Maps Rest APIs .我经常使用Bing Maps Rest API You can geo-code using requests like the following:您可以使用如下请求进行地理编码:

http://dev.virtualearth.net/REST/v1/Locations/CA/adminDistrict/postalCode/locality/addressLine?includeNeighborhood=includeNeighborhood&key=BingMapsKey

You can see it in use in a codeproject article I wrote on reactive extensions .您可以在我写的关于反应式扩展codeproject 文章中看到它正在使用中。

For example, your address:例如,您的地址:

http://dev.virtualearth.net/REST/v1/Locations/US/1125%20E.%20102nd%20Street,%20Los%20Angeles,%20CA?key=Ai9-KNy6Al-r_ueyLuLXFYB_GlPl-c-_iYtu16byW86qBx9uGbsdJpwvrP4ZUdgD

Gives the following response:给出以下响应:

{
   "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"
}

Or ... for XML data, add o=xml :或者 ... 对于 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

Which gives:这使:

<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>

So the lat / long for your given address is (33.9, -118.2)所以给定地址的经纬度是 (33.9, -118.2)

Google Maps has a web service API that returns lat/long, and works well for major countries.谷歌地图有一个返回纬度/经度的网络服务 API,适用于主要国家。 See http://maps.google.com/maps/geo?q=1%205th%20ave,new%20york,ny,us for an example.有关示例,请参见http://maps.google.com/maps/geo?q=1%205th%20ave,new%20york,ny,us Different output formats are supported including CSV, http://maps.google.com/maps/geo?q=1%205th%20ave,new%20york,ny,us&output=csv , JSON, etc.支持不同的输出格式,包括 CSV、 http ://maps.google.com/maps/geo?q=1%205th% 20ave ,new%20york, ny ,us&output=csv、JSON 等。

I'm not familiar with geocoder.us, but Google maps definitely works well for US addresses.我不熟悉 geocoder.us,但谷歌地图绝对适用于美国地址。

Edit 1: See http://code.google.com/apis/maps/faq.html#whatcountries for a list of countries supported编辑 1:有关支持的国家/地区列表,请参阅http://code.google.com/apis/maps/faq.html#whatcountries

Edit 2: For greater relevance, here's a sample Google Maps API call for your address in question: http://maps.google.com/maps/geo?q=1125%20E.%20102nd%20Street,%20Los%20Angeles,%20CA编辑 2:为了获得更大的相关性,以下是针对您的地址的示例 Google Maps API 调用: http : //maps.google.com/maps/geo?q=1125%20E.%20102nd%20Street,%20Los%20Angeles, %20CA

Get latitude and longitude by address - Microsoft BingMapsRESTToolkit按地址获取纬度和经度 - Microsoft BingMapsRESTToolkit

Microsoft has an official BingMapsRESTToolkit which helps you to work with Bing Maps REST Services easily. Microsoft 有一个官方的BingMapsRESTToolkit ,可帮助您轻松使用Bing Maps REST 服务 To do so, you need to install BingMapsRESTToolkit NuGet Package .为此,您需要安装 BingMapsRESTToolkit NuGet 包

Here, you are interested in GeocodeRequest to get location by address.在这里,您对GeocodeRequest感兴趣以按地址获取位置。 You can specify the address by setting Query property to the specified address or setting Address property to an instance of Address or SimpleAddress .您可以通过将Query属性设置为指定地址或将Address属性设置为AddressSimpleAddress的实例来指定地址。

Example:例子:

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
}

More information:更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM