SDKs overview
The Yandex.Maps Geocoder offers various methods for integration, primarily through its RESTful API. For client-side web development, the official Yandex.Maps JavaScript API provides integrated geocoding capabilities, allowing developers to perform forward and reverse geocoding operations directly within a web browser environment. Beyond the official JavaScript API, a range of community-contributed libraries extends support to other programming languages, simplifying interaction with the Geocoder API by handling request formatting, response parsing, and error management.
Developers using the Yandex.Maps Geocoder API can access core products such as the geocoding API for converting addresses to coordinates and the reverse geocoding API for converting coordinates to addresses. The developer experience is noted to be primarily supported by documentation in Russian, which may necessitate translation for non-Russian speaking developers, as detailed in the Yandex.Maps Geocoder documentation.
Official SDKs by language
Yandex primarily provides an official SDK for JavaScript, which integrates the Geocoder functionality directly into the Yandex.Maps JavaScript API. This allows developers to build interactive map applications with embedded geocoding capabilities without needing to make raw HTTP requests.
The official JavaScript API is the most robust and actively maintained solution for client-side integration, offering comprehensive features, event handling, and direct map visualization. For detailed usage, developers should consult the Yandex.Maps JavaScript API geocoding reference.
Official JavaScript SDK
The Yandex.Maps JavaScript API includes a dedicated geocoding module. This module allows for asynchronous geocoding requests and integrates seamlessly with map objects for displaying results.
| Language | Package/Module | Installation Command | Maturity |
|---|---|---|---|
| JavaScript | Yandex.Maps JavaScript API (includes Geocoder) | Included via script tag | Stable, Actively Maintained |
Installation
For the official Yandex.Maps JavaScript API with geocoding capabilities, installation involves embedding a script tag in your HTML file. This method loads the Yandex.Maps library directly into your web application.
JavaScript (Official)
To integrate the Yandex.Maps JavaScript API, including the Geocoder module, you need to include a script tag in your HTML. Replace YOUR_API_KEY with a key obtained from the Yandex Developer Console.
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&apikey=YOUR_API_KEY" type="text/javascript"></script>
After including the script, the API will be available globally, and you can initialize the map and use geocoding functions within your JavaScript code. Ensure your API key has the necessary permissions for the Geocoding service, which can be configured through the Yandex Developer Console, as outlined in the Yandex Maps JavaScript API quick start guide.
Quickstart example
This example demonstrates how to use the Yandex.Maps JavaScript API to perform a geocoding request and display the result on a map. This snippet assumes the Yandex.Maps JavaScript API has been loaded as described in the installation section.
JavaScript Quickstart (Official)
This code initializes a map, performs a geocoding request for a specific address, and then places a placemark on the map at the retrieved coordinates.
ymaps.ready(init);
function init() {
var myMap = new ymaps.Map('map', {
center: [55.753994, 37.622093], // Moscow coordinates for initial center
zoom: 10,
controls: []
});
// Geocoding an address
ymaps.geocode('Москва, улица Тверская, дом 13').then(function (res) {
var firstGeoObject = res.geoObjects.get(0),
coords = firstGeoObject.geometry.getCoordinates(),
bounds = firstGeoObject.properties.get('boundedBy');
myMap.geoObjects.add(firstGeoObject);
myMap.setBounds(bounds, { checkZoomRange: true }).then(function () {
if (myMap.getZoom() > 15) {
myMap.setZoom(15);
}
});
console.log('Address: ', firstGeoObject.getAddressLine());
console.log('Coordinates: ', coords);
// You can also add a placemark programmatically
var myPlacemark = new ymaps.Placemark(coords, {
iconContent: 'Tverskaya 13',
balloonContent: 'Москва, улица Тверская, дом 13'
}, {
preset: 'islands#redStretchyIcon'
});
myMap.geoObjects.add(myPlacemark);
});
// Example of reverse geocoding (coordinates to address)
ymaps.geocode([55.751244, 37.618423]).then(function (res) {
var firstGeoObject = res.geoObjects.get(0);
console.log('Reverse Geocoded Address: ', firstGeoObject.getAddressLine());
});
}
This example sets up a map and demonstrates both forward and reverse geocoding. The ymaps.ready() function ensures the API is fully loaded before executing the initialization code. For more advanced features, such as customizing geocoding options or handling multiple results, refer to the Yandex.Maps JavaScript API geocoding objects documentation.
Community libraries
While Yandex provides a core JavaScript API, the developer community has created libraries in other languages to facilitate interaction with the Yandex.Maps Geocoder REST API. These libraries often wrap the HTTP requests, provide convenient methods for parameters, and parse the JSON responses, abstracting the underlying API calls.
Python
Several Python libraries exist to interact with Yandex services, including geocoding. A popular approach is to use a library like yandex-maps or to construct requests using standard HTTP libraries like requests, which is a common practice for interacting with RESTful web services.
import requests
def geocode_yandex(address, api_key):
base_url = "https://geocode-maps.yandex.ru/1.x/"
params = {
"apikey": api_key,
"format": "json",
"geocode": address
}
response = requests.get(base_url, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
# Process the geocoding results
if data and data['response'] and data['response']['GeoObjectCollection'] and \
data['response']['GeoObjectCollection']['featureMember']:
first_object = data['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']
point_str = first_object['Point']['pos']
lat, lon = map(float, point_str.split(' '))
print(f"Address: {first_object['name']}, Coordinates: ({lat}, {lon})")
return lat, lon
else:
print("Geocoding failed or no results found.")
return None
# Example Usage:
# YOUR_YANDEX_GEOCODER_API_KEY = "YOUR_API_KEY"
# geocode_yandex("Moscow, Tverskaya street, 13", YOUR_YANDEX_GEOCODER_API_KEY)
PHP
For PHP applications, developers typically utilize standard HTTP client libraries (e.g., Guzzle) to make requests to the Yandex.Maps Geocoder API. While a dedicated, actively maintained official PHP SDK is not provided, building a wrapper function around HTTP requests is straightforward.
<?php
function geocodeYandex($address, $apiKey) {
$baseUrl = "https://geocode-maps.yandex.ru/1.x/";
$params = [
"apikey" => $apiKey,
"format" => "json",
"geocode" => $address
];
$queryString = http_build_query($params);
$url = $baseUrl . "?" . $queryString;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log("Yandex Geocoding API error: HTTP status code {$httpCode}");
return null;
}
$data = json_decode($response, true);
if (isset($data['response']['GeoObjectCollection']['featureMember'][0]['GeoObject'])) {
$geoObject = $data['response']['GeoObjectCollection']['featureMember'][0]['GeoObject'];
$pointStr = $geoObject['Point']['pos']; // longitude latitude
list($lon, $lat) = explode(' ', $pointStr);
echo "Address: " . $geoObject['name'] . ", Coordinates: ({$lat}, {$lon})\n";
return ['lat' => (float)$lat, 'lon' => (float)$lon];
} else {
echo "Geocoding failed or no results found.\n";
return null;
}
}
// Example Usage:
// define("YOUR_YANDEX_GEOCODER_API_KEY", "YOUR_API_KEY");
// geocodeYandex("Saint Petersburg, Nevsky Prospect, 1", YOUR_YANDEX_GEOCODER_API_KEY);
?>
Node.js
For Node.js environments, developers can use libraries like node-fetch or the built-in https module to interact with the Yandex.Maps Geocoder API. Community modules specifically targeting Yandex services may also be available on npm, offering a more abstracted interface.
const fetch = require('node-fetch'); // For Node.js environments without native fetch
async function geocodeYandexNode(address, apiKey) {
const baseUrl = "https://geocode-maps.yandex.ru/1.x/";
const params = new URLSearchParams({
apikey: apiKey,
format: "json",
geocode: address
});
const url = `${baseUrl}?${params.toString()}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data?.response?.GeoObjectCollection?.featureMember?.length > 0) {
const firstObject = data.response.GeoObjectCollection.featureMember[0].GeoObject;
const pointStr = firstObject.Point.pos; // longitude latitude
const [lon, lat] = pointStr.split(' ').map(Number);
console.log(`Address: ${firstObject.name}, Coordinates: (${lat}, ${lon})`);
return { lat, lon };
} else {
console.log("Geocoding failed or no results found.");
return null;
}
} catch (error) {
console.error("Error during geocoding:", error);
return null;
}
}
// Example Usage:
// const YOUR_YANDEX_GEOCODER_API_KEY = "YOUR_API_KEY";
// geocodeYandexNode("Yekaterinburg, Lenina Avenue, 50", YOUR_YANDEX_GEOCODER_API_KEY);
These community-driven approaches demonstrate how developers can integrate Yandex.Maps Geocoder functionality into various backend and frontend applications using standard language features and popular HTTP libraries. Developers are advised to check community repositories and package managers for the most up-to-date and maintained third-party libraries for their specific language and framework requirements.