2013-01-16 32 views
14

Ho un servizio WCF in C#. Nel client di chiamata del servizio invia un nome di città. Voglio convertire il nome della città in latitudini e longitudini e memorizzarlo nel database in base ai dati demografici. Sto pianificando di utilizzare l'API di Google per implementare le funzionalità di cui sopra. Ho ottenuto una chiave API da Google e il suo tipo di 'account di servizio'. SO ora Come posso ottenere la latitudine e la longitudine usando quali API? Devo installare qualche SDK o qualsiasi servizio REST lo farà?C# - Come trovare latitudine e longitudine usando C#

risposta

16

Se si desidera utilizzare l'API di Google Maps dare un'occhiata al loro API REST, non è necessario installare un API di Google Maps è sufficiente inviare una richiesta come

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

e si otterrà una risposta XML.

Per ulteriori informazioni un'occhiata a

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

+0

può voi mostra come analizzare l'XML? che mal di testa! – TheOptimusPrimus

+1

Se si desidera JSON, è possibile utilizzare http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View ,+CA&sensor=false – hriziya

+0

Incredibile e molto utile –

47

Si potrebbe provare il pacchetto NuGet GoogleMaps.LocationServices, o solo rotazione del suo source code. Utilizza l'API REST di Google per ottenere lat/long per un dato indirizzo e viceversa, senza la necessità di una chiave API.

È usare in questo modo:

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

C'è qualche limite a questo? In prima risposta, Google ha detto chiaramente che non può usare legalmente tranne Google Maps e ha qualche limite specifico sul numero di richieste. – MaxRecursion

+1

Lo stesso limite della risposta sopra si applica a questo. È solo un wrapper C# attorno all'API REST. Vedi [il codice sorgente] (https://github.com/sethwebster/GoogleMaps.LocationServices/blob/master/GoogleMaps.LocationServices/GoogleLocationService.cs#L14) – khellang

+1

Questo mi ha risparmiato ore di analisi dell'XML. +1, questa è una soluzione elegante !! – TheOptimusPrimus

6

È possibile passare l'indirizzo url in particolare .. e ottenere latitudine e longitudine nel valore di ritorno 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

ma ho bisogno di ROOFTOP, ma non ho trovato il location_type in 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

Nel mio caso, la mappa di Google fornisce il risultato per l'indirizzo e questo metodo fornisce un valore nullo per il risultato lat/long, quale potrebbe essere il problema? –

+0

cos 'questo metodo non funzionerà con lat/long –

+0

Utilizza questa API per Geocoding inverso .: http://maps.google.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false –

Problemi correlati