זיהוי Lat, Long מכתובת string
1. יש לפתוח מחלקה חדשה בשם MyPlace
[Serializable]
public class MyPlace
{
public int place_id
{ get; set; }
public string licence
{ get; set; }
public string osm_type
{ get; set; }
public long osm_id {
get; set; }
public float lat { get; set; }
public float lon { get; set; }
public string type { get; set; }
public int
place_rank { get; set; }
public float
importance { get; set; }
public string
addresstype { get; set; }
public string name { get; set; }
public string
display_name { get; set; }
public string[]
boundingbox { get; set; }
}
2. להוסיף שתי פעולות במחלקת השרות שלכם (Utils.cs / DBHelper.cs)
private static T
DownloadAndDeserializeJsonData<T>(string url) where T : new()
{
using (var
webClient = new
WebClient())
{
var jsonData = string.Empty;
try
{
webClient.Headers.Add(HttpRequestHeader.UserAgent, "/");
jsonData =
webClient.DownloadString(url);
}
catch (Exception) { }
return string.IsNullOrEmpty(jsonData)
? new T()
:
JsonConvert.DeserializeObject<T>(jsonData);
}
}
public static
List<MyPlace> getLatLongByAddress(string address, string city)
{
List<MyPlace> data = new List<MyPlace>();
try
{
string rootURL = "https://nominatim.openstreetmap.org/search?q=";
string endUrl = "&format=json";
string url;
url = rootURL + address + "+" + city + endUrl;
data =
DownloadAndDeserializeJsonData<List<MyPlace>>(url);
if (data.Count == 0)
{
url = rootURL + city + "+ישראל" + endUrl;
data = DownloadAndDeserializeJsonData<List<MyPlace>>(url);
}
}
catch
{
// error
}
return data;
}
3. הקריאה
והשימוש
private PointLatLng getLatLongByStringAddress(string address,string city)
{
List<MyPlace> data =
Utils.getLatLongByAddress(address, city);
string latStr = "", lonStr = "";
if (data != null
&& data.Count > 0)
{
List<MyPlace> tmp = data.Where(x
=> x.addresstype == "way").ToList();
if (tmp.Count != 0)
{
latStr = tmp[0].lat.ToString();
lonStr = tmp[0].lon.ToString();
}
else
{
latStr = data[0].lat.ToString();
lonStr = data[0].lon.ToString();
}
txbLat.Text = latStr;
txbLong.Text = lonStr;
}
else
{
txbLat.Text = "32.034034";
txbLat.Text = "34.722760";
}
double lat = Convert.ToDouble(latStr);
double lon = Convert.ToDouble(lonStr);
PointLatLng p1 = new PointLatLng(lat, lon);
return p1;
}