Skip to content

Множественное геокодирование для API 2.1 #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: gh-pages
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Created by .gitignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm

## Directory-based project format
.idea/
/*.iml
# if you remove the above rule, at least ignore user-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# and these sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# and, if using gradle::
# .idea/gradle.xml
# .idea/libraries

## File-based project format
*.ipr
*.iws

## Additional for IntelliJ
out/

# generated by mpeltonen/sbt-idea plugin
.idea_modules/

# generated by JIRA plugin
atlassian-ide-plugin.xml

# generated by Crashlytics plugin (for Android Studio and Intellij)
com_crashlytics_export_strings.xml
47 changes: 47 additions & 0 deletions examples/2.1/multi-geocoder/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Пример множественного геокодирования для API 2.1</title>

<script src="http://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>

<!-- Класс множественного геокодирования -->
<script src="multi-geocoder.js" type="text/javascript"></script>
<script src="list-collection.js" type="text/javascript"></script>

<script type="text/javascript">
ymaps.ready(function () {
var map = new ymaps.Map('map', {
center: [ 55.734046, 37.588628 ],
zoom: 9,
behaviors: ['default', 'scrollZoom']
});

var mGeocoder = new MultiGeocoder({ boundedBy: map.getBounds() });

// Геокодирование массива адресов и координат.
mGeocoder.geocode([
"Москва, Слесарный переулок, д.3",
"Люберцы, Октябрьский проспект д.143",
[ 55.734046, 37.588628 ],
"Мытищи, ул. Олимпийский проспект, владение 13, корпус А",
"Москва, 3-я Хорошовская улица д.2, стр.1",
"Москва, Нижний Сусальный переулок, д.5, стр.4"
])
.then(function (res) {
// Асинхронно получаем коллекцию найденных геообъектов.
map.geoObjects.add(res.geoObjects);
},
function (err) {
console.log(err);
});
});
</script>
</head>

<body>
<div id="map" style="width: 800px; height: 400px;"></div>
</body>

</html>
63 changes: 63 additions & 0 deletions examples/2.1/multi-geocoder/list-collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
function ListCollection() {
ListCollection.superclass.constructor.apply(this, arguments);
this._list = [];
}

ymaps.ready(function () {
ymaps.util.augment(ListCollection, ymaps.GeoObjectCollection, {
get: function (index) {
return this._list[index];
},
add: function (child, index) {
this.constructor.superclass.add.call(this, child);

index = index == null ? this._list.length : index;
this._list[index] = child;

return this;
},
indexOf: function (o) {
for (var i = 0, len = this._list.length; i < len; i++) {
if (this._list[i] === o) {
return i;
}
}

return -1;
},
splice: function (index, number) {
var added = Array.prototype.slice.call(arguments, 2),
removed = this._list.splice.apply(this._list, arguments);

for (var i = 0, len = added.length; i < len; i++) {
this.add(added[i]);
}

for (var i = 0, len = removed.length; i < len; i++) {
this.remove(removed[i]);
}

return removed;
},
remove: function (child) {
this.constructor.superclass.remove.call(this, child);

// this._list.splice(this.indexOf(child), 1);
delete this._list[this.indexOf(child)];

return this;
},
removeAll: function () {
this.constructor.superclass.removeAll.call(this);

this._list = [];

return this;
},
each: function (callback, context) {
for (var i = 0, len = this._list.length; i < len; i++) {
callback.call(context, this._list[i]);
}
}
});
});
58 changes: 58 additions & 0 deletions examples/2.1/multi-geocoder/multi-geocoder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* @fileOverview
* Реализация множественного геокодирования для версии АПИ 2.1.
*
* @example
var multiGeocoder = new MultiGeocoder({ boundedBy : map.getBounds() });

multiGeocoder
.geocode(['Москва, Льва Толстого 16', [55.7, 37.5], 'Санкт-Петербург'])
.then(
function (res) {
map.geoObjects.add(res.geoObjects);
},
function (err) {
console.log(err);
}
);
*/

/**
* Класс для геокодирования списка адресов или координат.
* @class
* @name MultiGeocoder
* @param {Object} [options={}] Дефолтные опции мультигеокодера.
*/
function MultiGeocoder(options) {
this._options = options || {};
}

/**
* Функция множественнеого геокодирования.
* @function
* @name MultiGeocoder.geocode
* @param {Array} requests Массив строк-имен топонимов и/или геометрий точек (обратное геокодирование)
* @returns {Object} Как и в обычном геокодере, вернем объект-обещание.
*/

MultiGeocoder.prototype.geocode = function (requests, options) {
var self = this,
size = requests.length,
def = new ymaps.vow.Deferred(),
geoObjects = new ListCollection();

requests.forEach(function (request, index) {
ymaps.geocode(request, ymaps.util.extend({}, self._options, options))
.then(
function (response) {
var geoObject = response.geoObjects.get(0);
geoObject && geoObjects.add(geoObject, index);
--size || def.resolve({ geoObjects: geoObjects });
},
function (err) {
def.reject(err);
}
);
});
return def.promise();
};