
28.10.2018, 15:31
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Яндекс-карты: как из json достать координаты
Добрый день. Отправляю по API адрес, получаю в ответ:
{"response":{"GeoObjectCollection":{"metaDataPrope rty":{"GeocoderResponseMetaData":{"request":"Ла рушинский пер., 10, Москва","found":"1","results":"10"}},"featur eMember":[{"GeoObject":{"metaDataProperty":{"GeocoderMetaDat a":{"kind":"house","text":"Россия, Москва, Лаврушинский переулок, 10","precision":"exact","Address":{"country_code": "RU","postal_code":"119017","formatted":"Моск а, Лаврушинский переулок, 10","Components":[{"kind":"country","name":"Россия"},{"kind":" province","name":"Центральный федеральный округ"},{"kind":"province","name":"Москв а"},{"kind":"locality","name":"Москва"},{"k ind":"street","name":"Лаврушинский переулок"},{"kind":"house","name":"10"}]},"AddressDetails":{"Country":{"AddressLine":"Мо сква, Лаврушинский переулок, 10","CountryNameCode":"RU","CountryName":"Росс ия","AdministrativeArea":{"AdministrativeAreaNam e":"Москва","Locality":{"LocalityName":"Мо сква","Thoroughfare":{"ThoroughfareName":"Ла врушинский переулок","Premise":{"PremiseNumber":"10", "PostalCode":{"PostalCodeNumber":"119017"}}}}}}}}} ,"description":"Москва, Россия","name":"Лаврушинский переулок, 10","boundedBy":{"Envelope":{"lowerCorner":"37.616 449 55.739017","upperCorner":"37.62466 55.743649"}},"Point":{"pos":"37.620555 55.741333"}}}]}}}
Как от туда вытащить значение pos: `37.620555 55.741333`?
Заранее спасибо
|
|

28.10.2018, 16:00
|
 |
Тлен
|
|
Регистрация: 02.01.2010
Сообщений: 6,597
|
|
json.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos
__________________
29375, 35
|
|

28.10.2018, 18:13
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Сделал так:
function httpGet(fullUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", fullUrl, true);
xhr.send();
xhr.onreadystatechange = function() { // (3)
if (xhr.readyState === 4 && xhr.status === 200) { alert(xhr.responseText.GeoObjectCollection.featureMember[0].GeoObject.Point.pos);
}
}
}
Даёт ошибку: Uncaught TypeError: Cannot read property 'featureMember' of undefined at XMLHttpRequest.xhr.onreadystatechange
|
|

28.10.2018, 18:34
|
 |
Профессор
|
|
Регистрация: 27.05.2010
Сообщений: 33,148
|
|
__Alex__,
где
Сообщение от Aetae
|
response
|
?
|
|

28.10.2018, 18:53
|
 |
Тлен
|
|
Регистрация: 02.01.2010
Сообщений: 6,597
|
|
alert(JSON.parse(xhr.responseText).response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos);
__________________
29375, 35
|
|

29.10.2018, 10:38
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Aetae, Рони - большое спасибо 
|
|

29.10.2018, 11:30
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Понял, каким чудесным образом формируется эта строка:
let obj = JSON.parse(resp); // конвертируем из json в объект js //
obj = obj.response; // {GeoObjectCollection: {…}}
obj = obj.GeoObjectCollection; // {metaDataProperty: {…}, featureMember: Array(1)}
obj = obj.featureMember[0]; // GeoObject: {metaDataProperty: {…}, description: "Москва, Россия", name: "Лаврушинский переулок, 10", boundedBy: {…}, Point: {…}}
obj = obj.GeoObject.Point; // {pos: "37.620555 55.741333"}
const coords = obj.pos; // 37.620555 55.741333
|
|

29.10.2018, 12:53
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Как вернуть данные из коллбэк-функции?
Не могу понять, как вытащить данные из коллбэк-функции, подскажите, пожалуйста.
console.log(xhr(adress)); // undefined
function xhr(adress) {
const request = (resp) => {
// console.log(resp); // {"response":{"GeoObjectCollection": ...
let obj = JSON.parse(resp); // конвертируем из json в объект js //
obj = obj.response; // {GeoObjectCollection: {…}}
obj = obj.GeoObjectCollection; // {metaDataProperty: {…}, featureMember: Array(1)}
obj = obj.featureMember[0]; // GeoObject: {metaDataProperty: {…}, boundedBy: {…}, Point: {…}}
obj = obj.GeoObject.Point; // {pos: "37.620555 55.741333"}
const coords = obj.pos; // 37.620555 55.741333
return coords;
}
function httpGet(fullUrl) {
const xhr = new XMLHttpRequest();
xhr.open("GET", fullUrl, true);
xhr.send();
xhr.onreadystatechange = function() { // (3)
if (xhr.readyState === 4 && xhr.status === 200) {
const coords = request(xhr.responseText); // 37.620555 55.741333
return (coords);
}
}
}
const url = 'https://geocode-maps.yandex.ru/1.x/?';
const apikey = 'xxx&format=json&geocode=';
const fullUrl = url + apikey + adress;
return httpGet(fullUrl);
}
|
|

29.10.2018, 13:12
|
Профессор
|
|
Регистрация: 04.12.2012
Сообщений: 3,823
|
|
Попробуйте так:
xhr(adress).then(response=>console.log(response));
function xhr(adress) {
const request = (resp) => {
// console.log(resp); // {"response":{"GeoObjectCollection": ...
let obj = JSON.parse(resp); // конвертируем из json в объект js //
obj = obj.response; // {GeoObjectCollection: {…}}
obj = obj.GeoObjectCollection; // {metaDataProperty: {…}, featureMember: Array(1)}
obj = obj.featureMember[0]; // GeoObject: {metaDataProperty: {…}, boundedBy: {…}, Point: {…}}
obj = obj.GeoObject.Point; // {pos: "37.620555 55.741333"}
const coords = obj.pos; // 37.620555 55.741333
return coords;
}
function httpGet(fullUrl) {
return new Promise(resolve=>{
const xhr = new XMLHttpRequest();
xhr.open("GET", fullUrl, true);
xhr.onload=()=>{
resolve(
request(xhr.responseText)
);
};
xhr.send();
});
}
const url = 'https://geocode-maps.yandex.ru/1.x/?';
const apikey = 'xxx&format=json&geocode=';
const fullUrl = url + apikey + adress;
return httpGet(fullUrl);
}
|
|

29.10.2018, 14:24
|
Интересующийся
|
|
Регистрация: 18.06.2018
Сообщений: 21
|
|
Так работает, но при попытке вытащить координаты, случается следующее:
const coords = xhr(adress).then(response => response);
console.log(coords); // Promise {<pending>}__proto__: Promisecatch: ƒ catch()constructor: ƒ Promise()finally: ƒ finally()then: ƒ then()Symbol(Symbol.toStringTag): "Promise"__proto__: Object[[PromiseStatus]]: "resolved"[[PromiseValue]]: "37.637659 55.826291"
|
|
|
|