Reputation: 65
I want to get the latitude and longitude form the results of google geocoding API, but I don't know how to take out the latitude and longitude out using json. The results of google geocoding is like following:
[{
'address_components': [{
'long_name': 'Macau',
'short_name': 'MO',
'types': ['country', 'locality', 'political']
}],
'formatted_address': 'Macau',
'geometry': {
'bounds': {
'northeast': {
'lat': 22.2170639,
'lng': 113.6127001
},
'southwest': {
'lat': 22.1066001,
'lng': 113.5276053
}
},
'location': {
'lat': 22.198745,
'lng': 113.543873
},
'location_type': 'APPROXIMATE',
'viewport': {
'northeast': {
'lat': 22.2170639,
'lng': 113.6127001
},
'southwest': {
'lat': 22.1066001,
'lng': 113.5276053
}
}
},
'place_id': 'ChIJ88g14uB6ATQR9qyFtCzje8Y',
'types': ['country', 'locality', 'political']
}]
I only want to use:
'location': {
'lat': 22.198745,
'lng': 113.543873
},
and save them in two variables. How can I make it?
Upvotes: 1
Views: 65
Reputation: 7654
Copy Past your JSON to http://jsonviewer.stack.hu/ in 'Text' tab and check out the Viewer Tab.
You will see your tree view of your JSON string.
For location it is:
var obj = // your whole json object
var obj = JSON.parse(jsonString) // if you have JSON string not the object.
Then
var location = obj[0].geometry.location;
Here you have an array, so first, we accessing the first element with index = 0, obj[0]
tthen the geometry obj[0].geometry
and then the location obj[0].geometry.location
JSON is built on two structures:
var a = ['a', 'b', {'c': 'i am value of key c', 'd': 'i am value of key d'}, 10];
console.log('Array element: a[0] = ', a[0]);
console.log('Access inside property of object: a[2].c = ', a[2].c);
console.log('Another way of accessing property: a[2][\'c\'] = ', a[2]['c']);
console.log('Accessing with . notation seems easy: a[2].d = ', a[2].d);
console.log('Array element can be string, number, obj, array, etc: a[3] = ', a[3]);
Check with your example:
var a = [
{
'address_components':[
{
'long_name':'Macau',
'short_name':'MO',
'types':[
'country',
'locality',
'political'
]
}
],
'formatted_address':'Macau',
'geometry':{
'bounds':{
'northeast':{
'lat':22.2170639,
'lng':113.6127001
},
'southwest':{
'lat':22.1066001,
'lng':113.5276053
}
},
'location':{
'lat':22.198745,
'lng':113.543873
},
'location_type':'APPROXIMATE',
'viewport':{
'northeast':{
'lat':22.2170639,
'lng':113.6127001
},
'southwest':{
'lat':22.1066001,
'lng':113.5276053
}
}
},
'place_id':'ChIJ88g14uB6ATQR9qyFtCzje8Y',
'types':[
'country',
'locality',
'political'
]
}
];
// way 1
var locObj1 = a[0]['geometry']['location'];
// way 2
var locObj2 = a[0].geometry.location;
console.log("Way1: a[0]['geometry']['location'] = ", locObj1);
console.log("Way2: a[0].geometry.location = ", locObj1);
Upvotes: 1
Reputation: 200
You can access via object like :
const json = JSON.parse("<your_json>"); // your json between ""
and then
const location = json[0].geometry.location;
console.log (JSON.stringify(location );)
Upvotes: 0