javascript 更有效的提取地址成分的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8313876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
More efficient way to extract address components
提问by 0xbadf00d
Currenty, I'm using the following code to get the country, postal code, locality and sub-locality:
目前,我使用以下代码来获取国家、邮政编码、地区和子地区:
var country, postal_code, locality, sublocality;
for (i = 0; i < results[0].address_components.length; ++i)
{
for (j = 0; j < results[0].address_components[i].types.length; ++j)
{
if (!country && results[0].address_components[i].types[j] == "country")
country = results[0].address_components[i].long_name;
else if (!postal_code && results[0].address_components[i].types[j] == "postal_code")
postal_code = results[0].address_components[i].long_name;
else if (!locality && results[0].address_components[i].types[j] == "locality")
locality = results[0].address_components[i].long_name;
else if (!sublocality && results[0].address_components[i].types[j] == "sublocality")
sublocality = results[0].address_components[i].long_name;
}
}
That's unsatisfactory. Is there any other way to achieve the same result?
这是不令人满意的。有没有其他方法可以达到相同的结果?
采纳答案by 0xbadf00d
if (typeof Object.keys == 'function')
var length = function(x) { return Object.keys(x).length; };
else
var length = function() {};
var location = {};
for (i = 0; i < results[0].address_components.length; ++i)
{
var component = results[0].address_components[i];
if (!location.country && component.types.indexOf("country") > -1)
location.country = component.long_name;
else if (!location.postal_code && component.types.indexOf("postal_code") > -1)
location.postal_code = component.long_name;
else if (location.locality && component.types.indexOf("locality") > -1)
location.locality = component.long_name;
else if (location.sublocality && component.types.indexOf("sublocality") > -1)
location.sublocality = component.long_name;
// nothing will happen here if `Object.keys` isn't supported!
if (length(location) == 4)
break;
}
This is the most suitable solution for me. It may help someone too.
这是最适合我的解决方案。它也可以帮助某人。
回答by Johann
You could use the following function to extract any address component:
您可以使用以下函数来提取任何地址组件:
function extractFromAdress(components, type){
for (var i=0; i<components.length; i++)
for (var j=0; j<components[i].types.length; j++)
if (components[i].types[j]==type) return components[i].long_name;
return "";
}
To extract the info you call:
要提取您调用的信息:
var postCode = extractFromAdress(results[0].address_components, "postal_code");
var street = extractFromAdress(results[0].address_components, "route");
var town = extractFromAdress(results[0].address_components, "locality");
var country = extractFromAdress(results[0].address_components, "country");
etc...
等等...
回答by user1429980
My one-liner using a functional approach and map
, filter
, and ES2015:
使用功能的做法和我的一行map
,filter
和ES2015:
/**
* Get the value for a given key in address_components
*
* @param {Array} components address_components returned from Google maps autocomplete
* @param type key for desired address component
* @returns {String} value, if found, for given type (key)
*/
function extractFromAddress(components, type) {
return components.filter((component) => component.types.indexOf(type) === 0).map((item) => item.long_name).pop() || null;
}
Usage:
用法:
const place = autocomplete.getPlace();
const address_components = place["address_components"] || [];
const postal_code = extractFromAddress(address_components, "postal_code");
回答by Bergi
You can shorten it to
您可以将其缩短为
var country, postal_code, locality, sublocality;
for (i = 0; i < results[0].address_components.length; ++i) {
var component = results[0].address_components[i];
if (!sublocality && component.types.indexOf("sublocality") > -1)
sublocality = component.long_name;
else if (!locality && component.types.indexOf("locality") > -1)
locality = component.long_name;
else if (!postal_code && component.types.indexOf("postal_code") > -1)
postal_code = component.long_name;
else if (!country && component.types.indexOf("country") > -1)
country = component.long_name;
}
Or are you trying to get a better formatted result? Then please show us your query.
或者您是否想获得更好的格式化结果?那么请告诉我们您的查询。
回答by stef
I did it like this:
我是这样做的:
placeParser = function(place){
result = {};
for(var i = 0; i < place.address_components.length; i++){
ac = place.address_components[i];
result[ac.types[0]] = ac.long_name;
}
return result;
};
then i just use
然后我就用
parsed = placeParser(place)
parsed.route
回答by stef
I really believe that user1429980answer above deserves more recognition. It works really well. My answer is based on his function. I've added a few examples to better illustrate how to search the JSON object using the code user1429980 provided:
我真的相信上面user1429980 的回答值得更多认可。它真的很好用。我的回答是基于他的功能。我添加了一些示例以更好地说明如何使用提供的代码 user1429980 搜索 JSON 对象:
//searches object for a given key and returns the key's value
//searches object for a given key and returns the key's value
extractFromObject (object, key) {
return object.filter((component) => component.types.indexOf(key)
=== 0).map((item)=>item.long_name).pop() || null;
}
extractFromObject (object, key) {
return object.filter((component) => component.types.indexOf(key)
=== 0).map((item)=>item.long_name).pop() || null;
}
Example 1:Google's reverseGeocode API with longitude and latitude set at 43.6532,79.3832 (Toronto, Ontario, Canada):
示例 1:Google 的 reverseGeocode API,经度和纬度设置为 43.6532,79.3832(加拿大安大略省多伦多):
var jsonData = {} //object contains data returned from reverseGeocode API
var jsonData = {} //object contains data returned from reverseGeocode API
var city = extractFromObject(jsonData.json.results[0].address_components, 'locality');
var city = extractFromObject(jsonData.json.results[0].address_components, 'locality');
console.log(city); //Output is Toronto
console.log(city); //Output is Toronto
Example 2: Google's Places API with place ID set to ChIJE9on3F3HwoAR9AhGJW_fL-I (Los Angeles, CA, USA):
示例 2:Google 的 Places API,地点 ID 设置为 ChIJE9on3F3HwoAR9AhGJW_fL-I(美国加利福尼亚州洛杉矶):
var jsonData = {} //object contains data returned from Google's Places API
var jsonData = {} //object contains data returned from Google's Places API
var city = extractFromObject(jsonData.json.result.address_components, 'locality');
var city = extractFromObject(jsonData.json.result.address_components, 'locality');
console.log(city); //Output is Los Angeles
console.log(city); //Output is Los Angeles
回答by James
Using lodash
使用 lodash
const result = _.chain(json.results[0].address_components)
.keyBy('types[0]')
.mapValues('short_name')
.value()
回答by Jordan Arseno
Visitors using underscore.js can easily convert the address_components
array in the geocode response into an object literal:
使用 underscore.js 的访问者可以轻松地将address_components
地理编码响应中的数组转换为对象文字:
var obj = _.object(
_.map(results[0].address_components, function(c){
return [c.types[0], c.short_name]
})
);