Good day! I have such a question, there is a map , if you look at the code, then the coordinates are set in the script itself, how can the same coordinates be output from the JSON file?
Like now enter image description here As needed
enter image description here Data as you can see, I have already taken out a separate file, but how to pick up the coordinates, I can not think of it before (I use this solution , there is also an array, but I need it as you understood from the file.
Tell me please

  • Already made) The decision below) But it seems to me the best - Azamat Sharafutdinov
  • the main thing that works)) and the example above shows the "official" way of how to do this in 3 lines using API methods - Reni

1 answer 1

This problem was solved as follows.

function init() { var myMap = new ymaps.Map('msk_map',{ center: [55.7, 37.5], zoom: 9, controls: ['zoomControl'] }), myCollection = new ymaps.GeoObjectCollection(); $.getJSON('js/data.json', function(data) { for (var i in data.departments) { //Именно тут указываем координаты myPoints = [{ coords: [ data.departments[i].lat, // широта data.departments[i].lon // Долгота ], text: data.departments[i].title }] // Перебор for (var i = 0, l = myPoints.length; i < l; i++) { var point = myPoints[i]; myCollection.add(new ymaps.Placemark(point.coords,{ balloonContentBody: point.text })); } // Добавляем коллекцию меток на карту. myMap.geoObjects.add(myCollection); // Создаем экземпляр класса ymaps.control.SearchControl var mySearchControl = new ymaps.control.SearchControl({ options: { // Заменяем стандартный провайдер данных (геокодер) нашим собственным. provider: new CustomSearchProvider(myPoints), // Не будем показывать еще одну метку при выборе результата поиска, // т.к. метки коллекции myCollection уже добавлены на карту. noPlacemark: true, resultsPerPage: 5 } }); } // Провайдер данных для элемента управления ymaps.control.SearchControl. // Осуществляет поиск геообъектов в по массиву points. // Реализует интерфейс IGeocodeProvider. function CustomSearchProvider(points) { this.points = points; } // Провайдер ищет по полю text стандартным методом String.ptototype.indexOf. CustomSearchProvider.prototype.geocode = function(request, options) { var deferred = new ymaps.vow.defer() , geoObjects = new ymaps.GeoObjectCollection() , // Сколько результатов нужно пропустить. offset = options.skip || 0 , // Количество возвращаемых результатов. limit = options.results || 20; var points = []; // Ищем в свойстве text каждого элемента массива. for (var i = 0, l = this.points.length; i < l; i++) { var point = this.points[i]; if (point.text.toLowerCase().indexOf(request.toLowerCase()) != -1) { points.push(point); } } // При формировании ответа можно учитывать offset и limit. points = points.splice(offset, limit); // Добавляем точки в результирующую коллекцию. for (var i = 0, l = points.length; i < l; i++) { var point = points[i] , coords = point.coords , text = point.text; geoObjects.add(new ymaps.Placemark(coords,{ name: text + ' name', description: text + ' description', balloonContentBody: '<p>' + text + '</p>', boundedBy: [coords, coords] })); } deferred.resolve({ // Геообъекты поисковой выдачи. geoObjects: geoObjects, // Метаинформация ответа. metaData: { geocoder: { // Строка обработанного запроса. request: request, // Количество найденных результатов. found: geoObjects.getLength(), // Количество возвращенных результатов. results: limit, // Количество пропущенных результатов. skip: offset } } }); return deferred.promise(); } }); // Заполняем коллекцию данными. // Возвращаем объект-обещание. }; ymaps.ready(init); 

JSON file example

 { "new" : "test" , "departments": [ { "lat": "55.791901", "lon": "37.626301", "title": "СУЩЁВСКИЙ" } ] }