To retrieve a list of objects that appear as markers in the Yandex Map view, the approach depends on the version of the Yandex Maps API you're using (2.x or 3.x) and whether you're managing markers yourself or relying on the API's built-in methods. Here's a structured solution:
1. Using Yandex Maps API 3.x (Modern Version)
In the Yandex Maps API 3.x , markers are instances of the Marker class. You can use the map.getObjects() method to get all objects on the map and filter them to identify markers.
Code Example:
javascript Copy code
// Assuming 'map' is your initialized Yandex Map instance
const allObjects = map.getObjects();
const markers = allObjects.filter(obj => obj instanceof ymaps3.Marker);
// Example: Log marker coordinates
markers.forEach(marker => {
console.log(marker.geometry.getCoordinates());
});
Key Notes:
map.getObjects() returns an array of all map objects (markers, polylines, polygons, etc.).
Use instanceof ymaps3.Marker to filter only markers.
If you're using custom marker types , adjust the filtering accordingly.
2. Using Yandex Maps API 2.x (Legacy Version)
In the Yandex Maps API 2.x , markers are instances of ymaps.Marker. You can access all objects via map.objects and filter them.
Code Example:
javascript Copy code
// Assuming 'map' is your initialized Yandex Map instance
const allObjects = map.objects.get();
const markers = allObjects.filter(obj => obj instanceof ymaps.Marker);
// Example: Log marker coordinates
markers.forEach(marker => {
console.log(marker.geometry.getCoordinates());
});
Key Notes:
map.objects.get() returns an array of all objects.
Use instanceof ymaps.Marker to identify markers.
This version is deprecated, so consider upgrading to 3.x for better features.
3. Managing Markers Manually
If you're adding markers yourself (e.g., via new ymaps3.Marker()), maintain a list of markers for easy access:
Code Example:
javascript Copy code
const markers = [];
// Add a marker
const marker = new ymaps3.Marker([55.751244, 37.623371], {
iconColor: 'red'
});
map.add(marker);
markers.push(marker);
// Access the list
console.log(markers);
4. Filtering Visible Markers (Optional)
If you want only markers currently visible in the map viewport, check each marker's position against the map's bounds:
Code Example (API 3.x):
javascript Copy code
const bounds = map.getBounds();
const visibleMarkers = markers.filter(marker => {
const [lat, lon] = marker.geometry.getCoordinates();
return bounds.contains([lat, lon]);
});
Key Considerations
API Version : Ensure you're using the correct version (3.x vs. 2.x) and refer to the official documentation .
Custom Objects : If using custom marker types (e.g., icons, clusters), adjust filtering logic.
Performance : For large datasets, consider optimizing visibility checks.
By leveraging these methods, you can effectively retrieve and manage markers on a Yandex Map. Let me know if you need help with specific use cases!