有一种更好的方法可以从谷歌地图的地理编码中获取类型
本文关键字:谷歌地图 编码 取类型 获取 一种 方法 更好 | 更新日期: 2023-09-27 17:53:19
使用c#,我需要从谷歌地图得到每个地址类型,我使用foreach和赋值。有比下一个代码更好的方法吗?:
string street_number;
string route;
string locality;
string administrative_area_level_3;
string administrative_area_level_2;
string administrative_area_level_1;
string country;
foreach (var addressComp in result.results[0].address_components)
{
var addr = addressComp;
if (addr.types[0] == "street_number")
street_number = addr.long_name;
else if (addr.types[0] == "route")
route = addr.long_name;
else if (addr.types[0] == "locality")
locality = addr.long_name;
else if (addr.types[0] == "administrative_area_level_3")
administrative_area_level_3 = addr.long_name;
else if (addr.types[0] == "administrative_area_level_2")
administrative_area_level_2 = addr.long_name;
else if (addr.types[0] == "administrative_area_level_1")
administrative_area_level_1 = addr.long_name;
else if (addr.types[0] == "country")
country = addr.long_name;
}
对我来说更容易读的代码是这样的,使用Linq
List<TypeOfAddressComponent> addressComponents result.results[0].address_components);
Func<List<TypeOfAddressComponent>, String, String> getValueFromAddressComponent =
(addressComponents, typeName) => addressComponents.Single(a => a.types[0] == typeName)
.Select(a => a.long_name);
string streetNumber = getValueFromAddressComponent(addressComponents, "streetNumber");
string route = getValueFromAddressComponent(addressComponents, "route");
...
可能效率较低,但对我来说更容易阅读和简单。
使用switch语句代替:
switch(addr.types[0]) {
case "street_number":
street_number = addr.long_name;
break;
case "route":
route = addr.long_name;
break;
case "locality":
locality = addr.long_name;
break;
case "administrative_area_level_3":
administrative_area_level_3 = addr.long_name;
break;
case "administrative_area_level_2":
administrative_area_level_2 = addr.long_name;
break;
case "administrative_area_level_1":
administrative_area_level_1 = addr.long_name;
break;
case "country":
country = addr.long_name;
break;
default:
// Error: addr.long_name does not match a case.
break;
}
…或者像@Habib提到的使用字典:
Dictionary<string, string> geo_data = new Dictionary<string, string>();
foreach (var addressComp in result.results[0].address_components)
{
geo_data[addr.types[0]] = addr.long_name;
}
通过使用字典,代码的行数明显减少,但可读性也降低,而且可能更复杂。可能会保存您不会在应用程序中使用的结果中的数据,因此我会在您的情况下使用switch。