Search on a map
Geocoding
The API provides a geocoding service, which can determine an object's geographical coordinates based on its name (forward geocoding), or the opposite, find an object's name based on its coordinates (reverse geocoding).
Both types of geocoding (forward and reverse) are performed using the geocode function, which can be passed an object name as a string, or coordinates as an array.
var myGeocoder = ymaps.geocode("Petrozavodsk");
var myReverseGeocoder = ymaps.geocode([61.79,34.36]);
The geocode
function is asynchronous, meaning that data is exchanged with the server while it is being executed.
Asynchronous interaction is implemented using promises. Invoking the geocode
function causes immediate creation of a vow.Promise type object, which performs the set functions when either geocoding results or an error message are returned from the server.
The result of the geocode
function is passed to the callback function as a GeoObjectCollection collection. This object implements the IGeoObject interface, meaning it can be placed on the map.
var myGeocoder = ymaps.geocode("Petrozavodsk");
myGeocoder.then(
function (res) {
alert('Object coordinates:' + res.geoObjects.get(0).geometry.getCoordinates());
},
function (err) {
alert('Error');
}
);
Geocoding results are passed to the callback function either as a GeoObjectCollection collection (by default) or in JSON format. The format of returned data is set in the json
option (true/false). For more information about the format of returned data, see Search on the map.
The search can be performed across the entire world map, or in a specified bounding box. However, a bounding box might not strictly restrict the search. This means the search will be performed across the entire map, but the closer a found object is to the center of the bbox, the higher it will be ranked in the results.
For reverse geocoding, the type of object to find can be specified (such as building, street, neighborhood, town, or metro station).
Found objects are ranked based on their distance from the set point.
var myCoords = [55.754952,37.615319];
myMap.geoObjects.add(
new ymaps.Placemark(myCoords,
{iconContent: 'Where is the metro?'},
{preset: 'islands#greenStretchyIcon'}
)
);
var myGeocoder = ymaps.geocode(myCoords, {kind: 'metro'});
myGeocoder.then(
function (res) {
var nearest = res.geoObjects.get(0);
var name = nearest.properties.get('name');
nearest.properties.set('iconContent', name);
nearest.options.set('preset', 'islands#redStretchyIcon');
myMap.geoObjects.add(res.geoObjects);
},
function (err) {
alert('Error');
}
);
When searching for streets, neighborhoods/regions, or cities/towns, their respective buildings are not included, regardless of size.
var myGeocoder = ymaps.geocode('Noviy Arbat, 10');
myGeocoder.then(
function (res) {
var coords = res.geoObjects.get(0).geometry.getCoordinates();
var myGeocoder = ymaps.geocode(coords, {kind: 'street'});
myGeocoder.then(
function (res) {
var street = res.geoObjects.get(0);
var name = street.properties.get('name');
// Outputs "Bolshaya Molchanovka street",
// even though reverse geocoding
// gives the coordinates of building 10 on Noviy Arbat street.
alert(name);
}
);
});
The «Search on map» control
The «Search on map» control gives users the ability to search for desired objects on the map. When a user enters a query in the search box, the API automatically performs a search and then displays the results on the map. Users can search for objects either by address or by geographical coordinates. In addition, this control can be used to search for businesses.
The «Search on map» control is implemented by the control.SearchControl class. The example below shows how to add this control to the map:
// Creating the «Search on map» control.
var searchControl = new ymaps.control.SearchControl({
options: {
// Search will be performed across toponyms and businesses.
provider: 'yandex#search'
}
});
// Adding the control to the map.
myMap.controls.add(searchControl);
Note
To make it possible to search for businesses as well as toponyms, pass the provider: 'yandex#search'
option to the control.SearchControl
class.
To programmatically perform a search for some object, call the search() function. The search for objects will be performed within the current bounding box.
searchControl.search('Starbucks');
The control.SearchControl
class provides the following methods for working with search results:
getResult
A method that returns an object found at the specified index. The method works asynchronously. It returns a Promise object that is resolved by the found object or rejected with an error.
var searchControl = new ymaps.control.SearchControl({
options: {
// The search will be performed across toponyms and businesses.
provider: 'yandex#search'
}
});
var result = searchControl.getResult(0);
result.then(function (res) {
console.log("Results " + res );
}, function (err) {
console.log("Error");
});
getResultsArray
Returns an array containing all current results.
var searchControl = new ymaps.control.SearchControl({
options: {
// The search will be performed across toponyms and businesses
provider: 'yandex#search'
}
});
// Subscribing to the search result selection event.
searchControl.events.add('resultselect', function (e) {
// Getting the results array.
var results = searchControl.getResultsArray(),
// Index of the selected object.
selected = e.get('index'),
// Getting the coordinates of the selected object.
point = results[selected].geometry.getCoordinates();
})
getResponseMetaData
Returns the geo search metadata.
var searchControl = new ymaps.control.SearchControl({
options: {
// The search will be performed across toponyms and businesses.
provider: 'yandex#search'
}
});
searchControl.search('Starbucks');
searchControl.events.add('resultselect', function (e) {
var index = e.get('index'),
results = searchControl.getResponseMetaData();
console.log(results.SearchRequest.request); // Starbucks
console.log(results.SearchRequest.results); // 20
})
getResultsCount
Returns the number of results found.
var searchControl = new ymaps.control.SearchControl({
options: {
// The search will be performed across toponyms and businesses.
provider: 'yandex#search'
}
});
// Subscribing to the event of getting search results from the server.
searchControl.events.add('load', function (e) {
var count = searchControl.getResultsCount();
console.log("Number of search results found: " + count);
})
getSelectedIndex
Returns the index of the selected item.
var searchControl = new ymaps.control.SearchControl({
options: {
// The search will be performed across toponyms and businesses.
provider: 'yandex#search'
}
});
// Subscribing to the event of getting search results from the server.
searchControl.events.add('resultselect', function (e) {
var index = searchControl.getSelectedIndex(e);
console.log("Index of the selected element: " + index);
})
showResult
Displays the result on the map.
// We want to always show the first result
// regardless of the number of objects
// found on the map (1 or more).
var searchControl = new ymaps.control.SearchControl({
options: {
noSelect: true
}
});
searchControl.events.add('load', function (event) {
// Checking that this event isn't just finishing loading results
// and the query has at least one result found.
if (!event.get('skip') && searchControl.getResultsCount()) {
searchControl.showResult(0);
}
});
hideResult
Hides the result shown on the map.
// If we displayed a result on the map using control.SearchControl.showResult
// or it was shown automatically when searching, we can hide it,
// for example, by clicking a button.
var myButton = new ymaps.control.Button("Hide results");
myButton.events.add('click', function () {
searchControl.hideResult();
}, this);
myMap.controls.add(myButton, {
selectOnClick: false
});
All the available methods are listed in the reference guide.
You can look at the example of using control.SearchControl
in the sandbox.