2013-01-16 13 views
14

Mam usługi WCF w języku C#. W kliencie usługi połączenia wysyła nazwę miasta. Chcę zamienić nazwę miasta na szerokości i długości geograficzne i zapisać w bazie danych pod danymi demograficznymi. Mam zamiar użyć Google API do wdrożenia powyższych funkcji. Otrzymałem klucz API z Google i jego typ "Konto usługi". SO teraz Jak mogę uzyskać szerokość i długość geograficzną za pomocą jakich interfejsów API? Czy muszę zainstalować SDK lub usługę REST?C# - Jak znaleźć szerokość i długość geograficzną za pomocą C#

Odpowiedz

16

Jeśli chcesz korzystać z interfejsu API Map Google rzucić okiem na ich REST API, nie trzeba zainstalować Google Maps API tylko wysłać żądanie jak

http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false 

a dostaniesz odpowiedź XML.

Aby uzyskać więcej informacji zajrzyj na

https://developers.google.com/maps/documentation/geocoding/index#GeocodingRequests

+0

może cię pokazać, jak parsować XML? co za ból głowy! – TheOptimusPrimus

+1

Jeśli chcesz JSON, możesz użyć http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway ,+Mountain+View,+CA&sensor=false – hriziya

+0

Niesamowite i bardzo pomocne –

47

Można wypróbować pakiet Nuget GoogleMaps.LocationServices, lub po prostu spin jego source code. Korzysta z interfejsu API REST Google do uzyskiwania informacji o długości/długości dla danego adresu i na odwrót, bez konieczności użycia klucza API.

go używać tak:

public static void Main() 
{ 
    var address = "Stavanger, Norway"; 

    var locationService = new GoogleLocationService(); 
    var point = locationService.GetLatLongFromAddress(address); 

    var latitude = point.Latitude; 
    var longitude = point.Longitude; 

    // Save lat/long values to DB... 
} 
+0

Czy jest w tym jakiś limit? W pierwszej odpowiedzi Google wyraźnie powiedział, że nie może używać legalnie z wyjątkiem map google i ma określony limit liczby żądań. – MaxRecursion

+1

Obowiązuje ten sam limit, co powyższa odpowiedź. To tylko opakowanie C# wokół interfejsu API REST. Zobacz [kod źródłowy] (https://github.com/sethwebster/GoogleMaps.LocationServices/blob/master/GoogleMaps.LocationServices/GoogleLocationService.cs#L14) – khellang

+1

To zaoszczędziło mi godziny przetwarzania XML. +1, to jest eleganckie rozwiązanie !! – TheOptimusPrimus

6

Można przekazać adres URL w szczególności .. i masz długość i szerokość geograficzną wartości powrót dt (DataTable)

string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address+ "&sensor=false"; 
WebRequest request = WebRequest.Create(url); 

using (WebResponse response = (HttpWebResponse)request.GetResponse()) 
{ 
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) 
    { 
     DataSet dsResult = new DataSet(); 
     dsResult.ReadXml(reader); 
     DataTable dtCoordinates = new DataTable(); 
     dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)), 
        new DataColumn("Address", typeof(string)), 
        new DataColumn("Latitude",typeof(string)), 
        new DataColumn("Longitude",typeof(string)) }); 
     foreach (DataRow row in dsResult.Tables["result"].Rows) 
     { 
      string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString(); 
      DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0]; 
      dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]); 
     } 
    } 
    return dtCoordinates; 
} 
+0

użyłem to ale potrzebuję ROOFTOP, ale nie znalazłem location_type w dsresult? – LuckyS

4
 /*Ready to use code : simple copy paste GetLatLong*/ 
    public class AddressComponent 
    { 
     public string long_name { get; set; } 
     public string short_name { get; set; } 
     public List<string> types { get; set; } 
    } 

    public class Northeast 
    { 
     public double lat { get; set; } 
     public double lng { get; set; } 
    } 

    public class Southwest 
    { 
     public double lat { get; set; } 
     public double lng { get; set; } 
    } 

    public class Bounds 
    { 
     public Northeast northeast { get; set; } 
     public Southwest southwest { get; set; } 
    } 

    public class Location 
    { 
     public double lat { get; set; } 
     public double lng { get; set; } 
    } 

    public class Northeast2 
    { 
     public double lat { get; set; } 
     public double lng { get; set; } 
    } 

    public class Southwest2 
    { 
     public double lat { get; set; } 
     public double lng { get; set; } 
    } 

    public class Viewport 
    { 
     public Northeast2 northeast { get; set; } 
     public Southwest2 southwest { get; set; } 
    } 

    public class Geometry 
    { 
     public Bounds bounds { get; set; } 
     public Location location { get; set; } 
     public string location_type { get; set; } 
     public Viewport viewport { get; set; } 
    } 

    public class Result 
    { 
     public List<AddressComponent> address_components { get; set; } 
     public string formatted_address { get; set; } 
     public Geometry geometry { get; set; } 
     public string place_id { get; set; } 
     public List<string> types { get; set; } 
    } 

    public class RootObject 
    { 
     public List<Result> results { get; set; } 
     public string status { get; set; } 
    } 


    public static RootObject GetLatLongByAddress(string address) 
    { 
     var root = new RootObject(); 

     var url = 
      string.Format(
       "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true_or_false", address); 
     var req = (HttpWebRequest)WebRequest.Create(url); 

     var res = (HttpWebResponse)req.GetResponse(); 

     using (var streamreader=new StreamReader(res.GetResponseStream())) 
     { 
      var result = streamreader.ReadToEnd(); 

      if (!string.IsNullOrWhiteSpace(result)) 
      { 
       root = JsonConvert.DeserializeObject<RootObject>(result); 
      } 
     } 
     return root; 


    } 


      /* Call This*/ 

var destination_latLong = GetLatLongByAddress(um.RouteDestination); 

var lattitude =Convert.ToString(destination_latLong.results[0].geometry.location.lat, CultureInfo.InvariantCulture); 

var longitude=Convert.ToString(destination_latLong.results[0].geometry.location.lng, CultureInfo.InvariantCulture); 
+0

W moim przypadku mapa Google podaje wynik dla adresu, a ta metoda podaje wartość pustą dla wyniku długości/długości, co może być problemem? –

+0

cos 'ta metoda nie będzie działać z lat/długo –

+0

Użyj tego API do odwrotnego geokodowania .: http://maps.google.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false –

Powiązane problemy