Directory
You can search for objects in the 2GIS directory, handle search results, and use suggestions to refine search queries. The directory contains information about objects of the following types:
- companies and their branches
- buildings
- parking lots
- public transport stops and metro stations
- roads (streets, intersections, driveways)
- settlements of various sizes (countries, cities, regions, villages, neighborhoods, etc.)
- various area objects (parks, beaches, etc.)
See the full list of available object types in the ObjectType class description.
To start working with the directory:
- Create a search engine.
- Build a search query.
- Get, handle, and display search results on the map.
Creating a search engine
To search for objects in the directory, create a SearchManager object and call one of the methods that determines the directory operating mode:
- SearchManager.createOnlineManager() - creates an online directory.
SearchManager.createOfflineManager()- creates an offline directory that works only with preloaded data. The method is available in the Full version of the SDK.SearchManager.createSmartManager()- creates a combined directory that works with online data when a network connection is available and with preloaded data when it is unavailable. The method is available in the Full version of the SDK.
Example of creating a search engine with an online directory:
import { SearchManager } from '@2gis/dgis-mobile-sdk-full';
const onlineSearchManager = SearchManager.createOnlineManager(context);
Some methods work only in a specific directory mode. Limitations are mentioned in the method descriptions.
Building a search query
To send a search query, create a SearchQuery object using SearchQueryBuilder and pass it to the search() method.
A search query must contain three logical components:
-
Object search request (what to search for?). You can formulate the request using one of the methods below:
-
From a text string using the setQueryText() method. You can formulate a text request to search for a specific object (
Saint Basil's Cathedral) or to get a list of multiple objects by a criterion (musical instrument stores). -
By category IDs using the setRubricIds() method. This method is useful for creating a selection of objects of a specific type.
-
By ID of:
- Organizations using the setOrgId() method. If a company has multiple branches, all locations will be listed in the response.
- Buildings using the setBuildingIds() method.
- Any objects using the searchByIds() and searchByDirectoryObjectIds() methods of the search engine.
-
-
Geographic restriction (where to search?). You can limit the search area using one of the methods below:
-
Search within a polygon: specify the search area using the setRestrictionGeometry() method and a PolygonGeometry object.
-
Search in a rectangular area of interest: specify coordinates using the setAreaOfInterest() method. This method sets a priority search area but does not strictly limit the search: if no results are found within the area of interest, the search will continue outside the area.
-
Search within a radius around a point: specify the search center using the setRestrictionGeometry() method and a PointGeometry object, and the radius using the setRadius() method.
-
Arbitrary query: if the object search query is formulated using the setQueryText() method, you can also specify the geographical restriction in the same text (
flowers near Baumanskaya).
-
-
(Optional component) Additional restrictions on search results using one or more of the methods below:
- Search for objects of a specific type only: list the object types you are interested in using the setAllowedResultTypes() method (for example, buildings only).
- Filter results: specify a filtering criterion using the setDirectoryFilter() method (for example, by working hours).
- Sort results: specify a sorting criterion using the setSortingType() method (for example, by rating).
- Number of results per page: set a limit using the setPageSize() method.
- Search results page number: the first page is returned by default. To get the next pages, use the fetchNextPage() method.
- Locale for the search query: specify the language and region using the setLocale() method.
Examples
-
Find Italian cuisine restaurants in the Presnensky District of Moscow that are currently open, sorted by rating:
import {
DirectoryFilter,
IsOpenNow,
SearchQueryBuilder,
SortingType,
WorkTimeFilter,
} from '@2gis/dgis-mobile-sdk-full';
const filter = new DirectoryFilter({
workTime: WorkTimeFilter.isOpenNow(new IsOpenNow({})),
dynamic: [],
});
const searchQuery = SearchQueryBuilder.fromQueryText(
'Italian restaurants in the Presnensky District of Moscow',
)
.setDirectoryFilter(filter)
.setSortingType(SortingType.ByRating)
.setPageSize(10)
.build(); -
Find all parking lots within a 1 km radius, sorted by distance:
import {
GeoPoint,
Latitude,
Longitude,
Meter,
ObjectType,
SearchQueryBuilder,
SortingType,
} from '@2gis/dgis-mobile-sdk-full';
const searchQuery = SearchQueryBuilder.fromQueryText('Parking')
.setAllowedResultTypes([ObjectType.Parking])
.setGeoPoint(
new GeoPoint({
latitude: new Latitude({ value: 59.936 }),
longitude: new Longitude({ value: 30.351 }),
}),
)
.setRadius(new Meter({ value: 1000 }))
.setSortingType(SortingType.ByDistance)
.build(); -
Find all settlements (cities, villages, towns, etc.) within a polygon:
import {
GeoPoint,
Latitude,
Longitude,
ObjectType,
PolygonGeometry,
SearchQueryBuilder,
} from '@2gis/dgis-mobile-sdk-full';
const point = (latitude: number, longitude: number) =>
new GeoPoint({
latitude: new Latitude({ value: latitude }),
longitude: new Longitude({ value: longitude }),
});
const polygon = new PolygonGeometry([
[
point(55.7, 37.5),
point(55.8, 37.5),
point(55.8, 37.7),
point(55.7, 37.7),
],
]);
const searchQuery = SearchQueryBuilder.fromQueryText('city name')
.setAllowedResultTypes([
ObjectType.AdmDivCity,
ObjectType.AdmDivSettlement,
])
.setRestrictionGeometry(polygon)
.build(); -
Find all objects that provide document printing services in an area of interest:
import {
GeoPoint,
GeoRect,
Latitude,
Longitude,
SearchQueryBuilder,
} from '@2gis/dgis-mobile-sdk-full';
const point = (latitude: number, longitude: number) =>
new GeoPoint({
latitude: new Latitude({ value: latitude }),
longitude: new Longitude({ value: longitude }),
});
const areaOfInterest = new GeoRect({
southWestPoint: point(59.931, 30.344),
northEastPoint: point(59.936, 30.351),
});
const searchQuery = SearchQueryBuilder.fromQueryText('document printing')
.setAreaOfInterest(areaOfInterest)
.build(); -
Find all companies at the address "Novosibirsk, Karl Marx Square, 7":
import {
ObjectType,
SearchQueryBuilder,
} from '@2gis/dgis-mobile-sdk-full';
const searchQuery = SearchQueryBuilder.fromQueryText(
'Novosibirsk, Karl Marx Square, 7',
)
.setAllowedResultTypes([ObjectType.Branch])
.setPageSize(10)
.build(); -
Find all branches of a company by a known ID:
import { OrgId, SearchQueryBuilder } from '@2gis/dgis-mobile-sdk-full';
const id = 4504136498310300n;
const searchQuery = SearchQueryBuilder.fromOrgId(
new OrgId({ value: id }),
).build(); -
Find a specific object by a known ID:
const future = searchManager.searchById('70000001006378335');
future.onComplete(
object => {
console.log(object?.title);
future.destroy();
},
error => {
console.warn(error);
},
);
Geocoding
With the SDK, you can do geocoding tasks: determine the coordinates of an object on the map by its address (direct geocoding) and vice versa, determine the address of an object on the map by its coordinates (reverse geocoding).
Direct geocoding
To get the coordinates of an object by its address, create a search query specifying the following details:
-
The address in the text query using the fromQueryText() method.
For more accurate results, specify the city (town or village) where the search is performed. The name of a small settlement (for example, a village) should be specified together with the region and other administrative areas it belongs to (for example, a rural or urban settlement).
-
(Recommended) The type of object whose coordinates you want to obtain using the setAllowedResultTypes() method.
-
(Recommended) The search area using the setAreaOfInterest() method.
For example, to get the coordinates of a building at the address "Moscow, 19a Tverskaya Street":
const geocodingQuery = SearchQueryBuilder.fromQueryText('Moscow, Tverskaya 19a')
.setAreaOfInterest(visibleRect)
.build();
In the search result, you will receive a DirectoryObject. The coordinates of the object are presented in the markerPosition field as a GeoPointWithElevation object. Example:
markerPosition:
GeoPointWithElevation {
latitude: Latitude { value: 55.7659 },
longitude: Longitude { value: 37.602827 },
elevation: Elevation { value: 18 },
},
See more about other information in search results in the Object data structure section.
Reverse geocoding
To get the address of an object by its coordinates, create a search query specifying the object coordinates as a strict search geometry. Use the setRestrictionGeometry() method and a PointGeometry object:
import {
GeoPoint,
Latitude,
Longitude,
PointGeometry,
SearchQueryBuilder,
} from '@2gis/dgis-mobile-sdk-full';
const searchQuery = new SearchQueryBuilder()
.setRestrictionGeometry(
new PointGeometry(
new GeoPoint({
latitude: new Latitude({ value: 55.7659 }),
longitude: new Longitude({ value: 37.602827 }),
}),
),
)
.build();
In the search result, you will receive DirectoryObject directory objects. The address of each object is presented in the address field as an Address object. Example:
address:
Address(
drillDown: [
AddressAdmDiv(type: 'country', name: 'Russia'),
AddressAdmDiv(type: 'region', name: 'Moscow'),
AddressAdmDiv(type: 'city', name: 'Moscow'),
AddressAdmDiv(type: 'district', name: 'Tverskoy'),
],
components: [
AddressComponent(
AddressStreet(
street: 'Tverskaya Street',
number: '19a',
fiasCode: null,
),
),
],
buildingName: null,
buildingId: BuildingId(value: 4504235282747324),
postCode: '125009',
buildingCode: null,
fiasCode: null,
addressComment: 'Floors 1-2',
),
See more about other information in search results in the Object data structure section.
Modifying search parameters
You can modify or add parameters to an already created search query. To do this, create a new SearchQuery object, specify the existing query using the fromQuery() method, and specify the parameters to be additionally applied. For example, change the sorting type for parking lot searches:
import {
GeoPoint,
Latitude,
Longitude,
Meter,
ObjectType,
SearchQueryBuilder,
SortingType,
} from '@2gis/dgis-mobile-sdk-full';
const searchQuery = SearchQueryBuilder.fromQueryText('Parking')
.setAllowedResultTypes([ObjectType.Parking])
.setGeoPoint(
new GeoPoint({
latitude: new Latitude({ value: 59.936 }),
longitude: new Longitude({ value: 30.351 }),
}),
)
.setRadius(new Meter({ value: 1000 }))
.setSortingType(SortingType.ByDistance)
.build();
const searchQueryUpdated = SearchQueryBuilder.fromQuery(searchQuery)
.setSortingType(SortingType.ByRating)
.build();
The other parameters of the initial query remain unchanged.
Getting search results
Calling the SearchManager.search() method returns a deferred Future<SearchResult>, which contains a paginated list of found objects (DirectoryObject). The first page of search results is available through the firstPage property.
const future = searchManager.search(textQuery);
future.onComplete(
result => {
const firstPage = result.firstPage;
const objects = firstPage?.items ?? [];
objects.forEach(object => {
console.log(object.title, object.subtitle);
});
future.destroy();
},
error => {
console.warn(error);
},
);
To get the next page, call the fetchNextPage() page method, which returns a deferred Page:
const nextPageFuture = firstPage.fetchNextPage();
nextPageFuture.onComplete(
page => {
console.log(page?.items ?? []);
nextPageFuture.destroy();
},
error => {
console.warn(error);
},
);
Displaying results on the map
The coordinates of all found objects are returned in the itemMarkerInfos field of the SearchResult as a list of ItemMarkerInfo elements. The list may contain no more than 15000 elements.
To display markers for all found objects on the map:
- Prepare a list of Marker objects. To set the marker position (the
positionparameter), use the coordinates from the ItemMarkerInfo.geoPoint field. - Add the prepared set of markers to the map using the
addObjects()method of the MapObjectManager. For more details, see the guide Adding multiple objects to the map.
import {
ImageLoader,
MapObjectManager,
Marker,
MarkerOptions,
type ItemMarkerInfo,
type Map,
type SearchResult,
} from '@2gis/dgis-mobile-sdk-full';
async function displaySearchResultMarkers(
map: Map,
searchResult: SearchResult,
) {
// Retrieve marker data from the search results
const markerInfosFuture = searchResult.itemMarkerInfos;
const markerInfos = await new Promise<ItemMarkerInfo[] | null>(
(resolve, reject) => {
markerInfosFuture.onComplete(
result => {
markerInfosFuture.destroy();
resolve(result);
},
error => {
reject(error);
},
);
},
);
if (markerInfos === null) {
return;
}
// Load the marker icon
const imageLoader = new ImageLoader(context);
const icon = await imageLoader.loadPngFromAsset(
'map/marker.png',
48,
48,
);
// Prepare the list of markers
const markers = markerInfos.map(
itemMarkerInfo =>
new Marker(
new MarkerOptions({
position: itemMarkerInfo.geoPoint,
icon,
}),
),
);
// Create an object manager and add markers to the map
const mapObjectManager = new MapObjectManager(map, null);
mapObjectManager.addObjects(markers);
}
Object data structure
Search results from the directory are presented as a list of DirectoryObject objects with sets of properties. Depending on the object type, some properties may not have values.
Access to certain information about objects is only available with additional key configuration for an extra fee: see the field descriptions of DirectoryObject, Address, and ItemMarkerInfo objects. Contact 2GIS support service to update your access key settings.
-
Main properties for object classification:
- Object type (
types) from ObjectType. One object can belong to several types (for example, the Sun City shopping center is both an organization branch and a building). In this case, all types will be listed, with the first element being the main object type. - Object name (
title) depending on its type: organization name, landmark, or geographic object. For residential buildings without a name, the address. - Object subtype (
subtitle) to clarify the classification. For example, a coffee shop as a subtype of an organization or a residential building as a subtype of a building. - Object description (
description). - Categories that the object belongs to (
rubricIds). - Organization identifier in the directory and information about it (
orgInfo). For companies with multiple branches, information about the head organization. - (Data on demand) Grouping of objects of different types in a single directory card (
group). See more below.
- Object type (
-
Unique object identifier in the directory (
id). For companies with multiple branches, the identifier of the particular branch. -
Geographic properties:
- Coordinates for placing a marker on the map (
markerPosition). - Full address of the object (
address). Some address components are available only on demand: see the Address object description. - (Data on demand) Information about the building floor where the object is located (
levelIdandbuildingLevels). Relevant for companies located on a specific floor of a multi-story building. - (Data on demand) Information about entrances to the object (
entrances) with coordinates and other data. Relevant not only for companies and buildings but also for other objects with physically designated entrances (for example, parks). - (Data on demand) Additional information to clarify the address (
titleAddition). For example, entrance number or apartment number.
- Coordinates for placing a marker on the map (
-
Working hours:
- Offset of the object's local time from UTC in timestamp form (
timeZoneOffset). For example,03:00:00for the UTC+3 timezone. - Working hours (
openingHours) as a list of time intervals or a round-the-clock flag. Relevant for companies. - Current work status (
workStatus). Relevant for organizations.
- Offset of the object's local time from UTC in timestamp form (
-
Other data:
- (Data on demand) Information about the trade license of the organization (
tradeLicense). - Contact information for the organization (
contactInfos): phone number, email address, website and social network links, and others. - Object rating based on user reviews (
reviews). - Additional parking properties (
parkingInfo). - Additional charging station properties (
chargingStation). - Building information (
buildingInfo).
- (Data on demand) Information about the trade license of the organization (
Object grouping
In the directory, some geographical objects can be represented as a group of objects of different types. For example, a courthouse is both a standalone building and an organization within that building, meaning two different DirectoryObject instances with characteristics of the building and the organization, respectively. Since these DirectoryObject instances belong to the same geographical object, their data structures contain references to each other.
Information about linked objects is stored in the group field as a list of GroupItem elements. Each linked object has a type and identifier (DgisObjectId), which you can later use to access the object.
Access to data in the group field is only available with additional key configuration for an extra fee. Contact 2GIS support service to update your access key settings.
Example of the group field populated with one linked object:
group: [
GroupItem(
id: DgisObjectId(objectId: 70030076538159915, entranceId: 0),
type: ObjectType.attraction,
),
],
Examples
Below are examples of DirectoryObject for different types of directory objects.
-
Organization branch:
DirectoryObject// Object type - organization
types: [ObjectType.branch],
// Organization name
title: 'Shokoladnitsa',
titleAddition: null,
// Organization subtype - coffee shop
subtitle: 'Coffee shop',
// Object ID (particular organization branch)
id: DgisObjectId(objectId: 4504128908451067, entranceId: 0),
// Coordinates of the marker to place on the map
markerPosition: GeoPointWithElevation(
latitude: Latitude(value: 55.7659),
longitude: Longitude(value: 37.602827),
elevation: Elevation(value: 18.0),
),
// Organization address - Moscow, 19a Tverskaya Street
address: Address(
drillDown: [
AddressAdmDiv(type: 'country', name: 'Russia'),
AddressAdmDiv(type: 'region', name: 'Moscow'),
AddressAdmDiv(type: 'city', name: 'Moscow'),
AddressAdmDiv(type: 'district', name: 'Tverskoy'),
],
components: [
AddressComponent(
AddressStreet(
street: 'Tverskaya Street',
number: '19a',
fiasCode: null,
),
),
],
buildingName: null,
buildingId: BuildingId(value: 4504235282747324),
postCode: '125009',
buildingCode: null,
fiasCode: null,
addressComment: 'Floors 1-2',
),
attributes: [],
contextAttributes: [],
// Local timezone - UTC+3
timeZoneOffset: Duration(hours: 3),
// Branch opening hours: Monday through Thursday from 7:00 to 23:00, Friday from 7:00 to 24:00,
// Saturday around the clock, and Sunday from 0:00 to 23:00
openingHours: OpeningHours(
weekOpeningHours: [
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.monday, time: DayTime(hours: 7, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.monday, time: DayTime(hours: 23, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.tuesday, time: DayTime(hours: 7, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.tuesday, time: DayTime(hours: 23, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.wednesday, time: DayTime(hours: 7, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.wednesday, time: DayTime(hours: 23, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.thursday, time: DayTime(hours: 7, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.thursday, time: DayTime(hours: 23, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.friday, time: DayTime(hours: 7, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.friday, time: DayTime(hours: 24, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.saturday, time: DayTime(hours: 0, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.saturday, time: DayTime(hours: 24, minutes: 0)),
),
],
[
WeekTimeInterval(
startTime: WeekTime(weekDay: WeekDay.sunday, time: DayTime(hours: 0, minutes: 0)),
finishTime: WeekTime(weekDay: WeekDay.sunday, time: DayTime(hours: 23, minutes: 0)),
),
],
],
isOpen24x7: false,
),
contactInfos: [],
// Rating is 3.4 based on 85 reviews
reviews: Reviews(rating: 3.4, count: 85),
parkingInfo: null,
// The branch is currently open and will be until 23:00
workStatus: WorkStatus(
openStatus: OpenStatus.opened(Opened(null)),
openStatusHint: 'Open until 23:00',
scheduleHint: 'Today until 23:00',
breakHint: null,
),
levelId: null,
buildingLevels: null,
// The organization has one entrance
entrances: [
EntranceInfo(
id: DgisObjectId(objectId: 4504128908451067, entranceId: 70030076156031010),
buildingNumber: null,
porchName: null,
porchNumber: null,
apartmentRanges: [],
geometry: EntranceGeometry(
entrancePoints: [
GeoPoint(
latitude: Latitude(value: 55.76590646318491),
longitude: Longitude(value: 37.60283837242394),
),
],
entrancePolylines: [
[
GeoPoint(
latitude: Latitude(value: 55.765971),
longitude: Longitude(value: 37.602949),
),
GeoPoint(
latitude: Latitude(value: 55.765906),
longitude: Longitude(value: 37.602838),
),
],
],
),
),
],
chargingStation: null,
// The object belongs to three categories
rubricIds: [
RubricId(value: 162),
RubricId(value: 1203),
RubricId(value: 161),
],
// Information about the head organization and the total count of branches
orgInfo: OrgInfo(
branchCount: 225,
id: OrgId(value: 4504136498310300),
name: 'Shokoladnitsa, coffee shop',
),
group: [], -
Residential building:
DirectoryObject// Object type - building
types: [ObjectType.building],
// Object name - building address
title: '2nd Chernogryazskaya Street, 1',
titleAddition: null,
// Object subtype - residential building
subtitle: 'Residential building',
// Object ID
id: DgisObjectId(objectId: 4504235282792806, entranceId: 0),
// Coordinates of the marker to place on the map
markerPosition: GeoPointWithElevation(
latitude: Latitude(value: 55.760651),
longitude: Longitude(value: 37.545995),
elevation: Elevation(value: 3.0),
),
// Object address - Moscow, 1 2nd Chernogryazskaya Street
address: Address(
drillDown: [
AddressAdmDiv(type: 'country', name: 'Russia'),
AddressAdmDiv(type: 'region', name: 'Moscow'),
AddressAdmDiv(type: 'city', name: 'Moscow'),
AddressAdmDiv(type: 'district', name: 'Presnensky'),
],
components: [
AddressComponent(
AddressStreet(
street: '2nd Chernogryazskaya Street',
number: '1',
fiasCode: '91e0431b-5721-40b9-8bf0-5eb5377063a8',
),
),
],
buildingName: null,
buildingId: BuildingId(value: 4504235282792806),
postCode: '123100',
buildingCode: null,
fiasCode: null,
addressComment: null,
),
attributes: [],
contextAttributes: [],
timeZoneOffset: null,
openingHours: null,
contactInfos: [],
// The object has no reviews for calculating a rating
reviews: Reviews(rating: 0.0, count: 0),
parkingInfo: null,
workStatus: null,
levelId: null,
buildingLevels: null,
// The residential building has two entrances
entrances: [
EntranceInfo(
id: DgisObjectId(objectId: 4504235282792806, entranceId: 4504643304435799),
buildingNumber: null,
porchName: null,
porchNumber: null,
apartmentRanges: [],
geometry: EntranceGeometry(
entrancePoints: [
GeoPoint(
latitude: Latitude(value: 55.76073452440514),
longitude: Longitude(value: 37.54591428882596),
),
],
entrancePolylines: [
[
GeoPoint(
latitude: Latitude(value: 55.760822),
longitude: Longitude(value: 37.545949),
),
GeoPoint(
latitude: Latitude(value: 55.760735),
longitude: Longitude(value: 37.545914),
),
],
],
),
),
EntranceInfo(
id: DgisObjectId(objectId: 4504235282792806, entranceId: 70030076156588095),
buildingNumber: null,
porchName: 'Entrance 1',
porchNumber: 1,
apartmentRanges: [
ApartmentRange(start: 1, end: 80),
],
geometry: EntranceGeometry(
entrancePoints: [
GeoPoint(
latitude: Latitude(value: 55.7605167221199),
longitude: Longitude(value: 37.54581996572112),
),
],
entrancePolylines: [
[
GeoPoint(
latitude: Latitude(value: 55.760497),
longitude: Longitude(value: 37.545975),
),
GeoPoint(
latitude: Latitude(value: 55.760517),
longitude: Longitude(value: 37.54582),
),
],
],
),
),
],
chargingStation: null,
rubricIds: [],
orgInfo: null,
group: [], -
Street:
DirectoryObject// Object type - street
types: [ObjectType.street],
// Object name
title: 'Petrova Street',
titleAddition: null,
// Object subtype - street
subtitle: 'Street',
// Object ID
id: DgisObjectId(objectId: 4504338361766218, entranceId: 0),
// Coordinates of the marker to place on the map
markerPosition: GeoPointWithElevation(
latitude: Latitude(value: 55.643536),
longitude: Longitude(value: 38.053038),
elevation: Elevation(value: 0.0),
),
// Object address - Udelnaya urban-type settlement, Moscow Region
address: Address(
drillDown: [
AddressAdmDiv(type: 'country', name: 'Russia'),
AddressAdmDiv(type: 'region', name: 'Moscow Region'),
AddressAdmDiv(type: 'district_area', name: 'Ramensky Municipal District'),
AddressAdmDiv(type: 'settlement', name: 'Udelnaya urban-type settlement'),
],
components: [],
buildingName: null,
buildingId: null,
postCode: null,
buildingCode: null,
fiasCode: '0d8e2b4c-eef7-4176-bbec-be9ac0ace587',
addressComment: null,
),
attributes: [],
contextAttributes: [],
timeZoneOffset: null,
openingHours: null,
contactInfos: [],
reviews: null,
parkingInfo: null,
workStatus: null,
levelId: null,
buildingLevels: null,
entrances: [],
chargingStation: null,
rubricIds: [],
orgInfo: null,
group: [], -
Area object (park):
DirectoryObject// Main object type - area object; additional type - landmark
types: [ObjectType.admDivPlace, ObjectType.attraction],
// Object name
title: 'Krasnogvardeyskiye Prudy Park',
titleAddition: null,
// Object subtype - place
subtitle: 'Place',
// Object ID
id: DgisObjectId(objectId: 4504286822138295, entranceId: 0),
// Coordinates of the marker to place on the map
markerPosition: GeoPointWithElevation(
latitude: Latitude(value: 55.756656),
longitude: Longitude(value: 37.545756),
elevation: Elevation(value: 0.0),
),
// Object address - Moscow
address: Address(
drillDown: [
AddressAdmDiv(type: 'country', name: 'Russia'),
AddressAdmDiv(type: 'region', name: 'Moscow'),
AddressAdmDiv(type: 'city', name: 'Moscow'),
],
components: [],
buildingName: null,
buildingId: null,
postCode: null,
buildingCode: null,
fiasCode: null,
addressComment: null,
),
attributes: [],
contextAttributes: [],
timeZoneOffset: null,
openingHours: null,
contactInfos: [],
// Rating is 4.8 based on 62 reviews
reviews: Reviews(rating: 4.8, count: 62),
parkingInfo: null,
workStatus: null,
levelId: null,
buildingLevels: null,
entrances: [],
chargingStation: null,
// The object belongs to one category
rubricIds: [RubricId(value: 168)],
orgInfo: null,
// The object is both an area object and a landmark
group: [
GroupItem(
id: DgisObjectId(objectId: 70030076538159915, entranceId: 0),
type: ObjectType.attraction,
),
],
Search suggestions
You can build text suggestions for users when they search for objects. To do this, create a SuggestQuery object using SuggestQueryBuilder and pass it to the suggest() method:
import {
SuggestHandlerKind,
SuggestQueryBuilder,
} from '@2gis/dgis-mobile-sdk-full';
const suggestQuery = SuggestQueryBuilder.fromQueryText('coff')
.setAreaOfInterest(map.camera.visibleRect)
.build();
const future = searchManager.suggest(suggestQuery);
future.onComplete(
result => {
result.suggests.forEach(suggest => {
switch (suggest.handler.kind) {
case SuggestHandlerKind.ObjectHandler:
console.log('Object:', suggest.handler.value.item.title);
break;
case SuggestHandlerKind.IncompleteTextHandler:
console.log('Complete:', suggest.handler.value.queryText);
break;
case SuggestHandlerKind.PerformSearchHandler: {
const searchFuture = searchManager.search(
suggest.handler.value.searchQuery,
);
searchFuture.onComplete(
searchResult => {
console.log(searchResult.firstPage?.items ?? []);
searchFuture.destroy();
},
error => {
console.warn(error);
},
);
break;
}
}
});
future.destroy();
},
error => {
console.warn(error);
},
);
The call returns a deferred SuggestResult, which contains a list of suggestions (Suggest). For more details on generating suggestions, see the Suggest API documentation.
When a user selects one of the suggested options, you can configure the reaction to this event using a SuggestHandler of one of the following types:
- SuggestObjectHandler - returns a DirectoryObject directory object.
- PerformSearchHandler - returns a SearchQuery search query object. You can use this object for further searches: pass it to the SearchManager.search() method or use it to create a new SearchQuery with additional parameters using the fromQuery() method (see the Modifying search parameters section).
- IncompleteTextHandler - returns the auto-completed suggestion text, which you can use to build a search query using the setQueryText() method.
Search history
You can work with the search history using SearchHistory.
The search history can contain two types of items: directory objects (DirectoryObject) and search queries (SearchQueryWithInfo).
You can get an instance using SearchHistory.instance(context).
Adding items to search history
You can add items to the search history as SearchHistoryItem objects, either one at a time or as a list. The order of items in the list is preserved when they are added to the history.
-
Create a
SearchHistoryItemfrom an object of the required type:- For a search query, use SearchQueryWithInfo. In addition to the search query, the object can contain a title and subtitle to display in the history.
- For a directory object, use DirectoryObject.
-
Get a
SearchHistoryinstance usingSearchHistory.instance(context). -
Add the prepared items one at a time using
addItem()or as a list usingaddItems().
import {
SearchHistory,
SearchHistoryItem,
SearchQueryWithInfo,
} from '@2gis/dgis-mobile-sdk-full';
const history = SearchHistory.instance(context);
history.addItem(SearchHistoryItem.directoryObject(directoryObject));
history.addItem(
SearchHistoryItem.searchQuery(
new SearchQueryWithInfo(textQuery, 'Coffee shops', 'Near me'),
),
);
To add multiple prepared items at once:
history.addItems(searchHistoryItems);
If an item already exists in the search history, the older duplicate is removed.
Displaying search history
To display a search history page with a list of items, create a SearchHistoryPage object and pass it to the items() method. You can also configure the following parameters:
- Limit the number of items per page (
limitparameter). The default value is 100. - Set an offset from the beginning of the list (
offsetparameter): the number of items to skip from the beginning. The default value is 0 (no offset, so the list is displayed from the beginning). - Filter the list by item type (
filterparameter). Available filters are listed in SearchHistoryFilter. For example, to show only search queries in the history, use thesearchQueryvalue. By default, no filtering is applied.
import { SearchHistoryPage } from '@2gis/dgis-mobile-sdk-full';
const future = history.items(new SearchHistoryPage({ limit: 20n }));
future.onComplete(
result => {
console.log(result.items);
future.destroy();
},
error => {
console.warn(error);
},
);
The items on the page are sorted by the time they were added, from newest to oldest.
Clearing search history
To remove specific items from the search history:
-
To remove a single item, pass the required
SearchHistoryItemto theremoveItem()method. For more details on creating aSearchHistoryItem, see Adding items to search history.history.removeItem(searchHistoryItem); -
To remove multiple items, pass a list of
SearchHistoryItemobjects to theremoveItems()method. For more details on creating aSearchHistoryItem, see Adding items to search history.history.removeItems(searchHistoryItems);
To completely clear the search history, call the clear() method:
history.clear();
Subscribing to history changes
To track items being added and removed, subscribe to the onHistoryChanged channel. The handler receives a ChangeType that indicates the type of change: Add or Remove.
const connection = history.onHistoryChanged.subscribe(change => {
console.log('History changed:', change);
});
connection.disconnect();
When tracking is no longer required, call disconnect() on the connection object.
Information about entrances in the directory
You can search for addresses in the directory with the exact apartment or entrance number.
For example, the query "Tomsk, Kirova Street, 17, apt. 5" returns an object with entrance-level details.
DgisObjectId contains two identifiers:
objectId- stable numeric identifier of the object.entranceId- stable numeric identifier of the object entrance.
If entranceId is not equal to 0n, the search result refers to a specific building entrance.
To place a marker at the found entrance or get its coordinates for route planning, do not use markerPosition: this field contains the marker position of the building itself. Find the entrance with the matching entranceId in the entrances field of the DirectoryObject and use the first point from geometry.entrancePoints. If the entrance geometry is unavailable, use the coordinates from markerPosition.
import { GeoPoint, type DirectoryObject } from '@2gis/dgis-mobile-sdk-full';
function getMarkerPosition(directoryObject: DirectoryObject): GeoPoint | null {
const entranceId = directoryObject.id?.entranceId ?? 0n;
if (entranceId === 0n) {
return null;
}
const entrance = directoryObject.entrances.find(
item => item.id.entranceId === entranceId,
);
const entrancePoint = entrance?.geometry?.entrancePoints[0];
if (entrancePoint !== undefined) {
return entrancePoint;
}
const markerPosition = directoryObject.markerPosition;
if (markerPosition === null) {
return null;
}
return new GeoPoint({
latitude: markerPosition.latitude,
longitude: markerPosition.longitude,
});
}