Размещение объекта
Объект Place, содержащий информацию о месте, динамически возвращается функциями текстового поиска, поиска поблизости и автозаполнения мест. Также можно создать объект Place на основе идентификатора места или названия ресурса (название ресурса – это идентификатор места с префиксом places/). В следующем фрагменте кода показано, как создать объект Place с помощью идентификатора места:
// Use a place ID to create a new Place instance. const place = new Place({ id: 'ChIJyYB_SZVU2YARR-I1Jjf08F0', // San Diego Zoo });
Вы также можете создать объект Place на основе названия ресурса места:
// Use a place resource name to create a new Place instance. const place = new Place({ resourceName: 'places/ChIJyYB_SZVU2YARR-I1JRF08F0', // San Diego Zoo });
Подробнее PlaceOptions…
Поля для получения
Если у вас уже есть объект Place, идентификатор места или название ресурса, используйте метод Place.fetchFields(), чтобы получить подробную информацию об этом месте. Укажите список полей данных о месте, которые нужно вернуть, через запятую. Названия полей должны быть в верблюжьем регистре. Используйте возвращенный объект Place, чтобы получить данные для запрошенных полей.
В примере ниже используется идентификатор места, чтобы создать новый объект Place, затем выполняется вызов метода Place.fetchFields() с запросом полей displayName и formattedAddress, а потом на карту добавляется маркер.
TypeScript
async function getPlaceDetails() { const [{ Place }, { AdvancedMarkerElement }] = await Promise.all([ google.maps.importLibrary('places'), google.maps.importLibrary('marker'), ]); // Use place ID to create a new Place instance. const place = new Place({ id: 'ChIJyYB_SZVU2YARR-I1Jjf08F0', // San Diego Zoo }); // Call fetchFields, passing the desired data fields. await place.fetchFields({ fields: [ 'displayName', 'formattedAddress', 'location', 'googleMapsURI', ], }); // Add an Advanced Marker const marker = new AdvancedMarkerElement({ map: innerMap, position: place.location, title: place.displayName, }); // Assemble the info window content. const content = document.createElement('div'); const address = document.createElement('div'); const placeId = document.createElement('div'); address.textContent = place.formattedAddress || ''; placeId.textContent = place.id; content.append(placeId, address); if (place.googleMapsURI) { const link = document.createElement('a'); link.href = place.googleMapsURI; link.target = '_blank'; link.textContent = 'View Details on Google Maps'; content.appendChild(link); } // Display an info window. infoWindow.setHeaderContent(place.displayName); infoWindow.setContent(content); infoWindow.open({ anchor: marker, }); }
JavaScript
async function getPlaceDetails() { const [{ Place }, { AdvancedMarkerElement }] = await Promise.all([ google.maps.importLibrary('places'), google.maps.importLibrary('marker'), ]); // Use place ID to create a new Place instance. const place = new Place({ id: 'ChIJyYB_SZVU2YARR-I1Jjf08F0', // San Diego Zoo }); // Call fetchFields, passing the desired data fields. await place.fetchFields({ fields: [ 'displayName', 'formattedAddress', 'location', 'googleMapsURI', ], }); // Add an Advanced Marker const marker = new AdvancedMarkerElement({ map: innerMap, position: place.location, title: place.displayName, }); // Assemble the info window content. const content = document.createElement('div'); const address = document.createElement('div'); const placeId = document.createElement('div'); address.textContent = place.formattedAddress || ''; placeId.textContent = place.id; content.append(placeId, address); if (place.googleMapsURI) { const link = document.createElement('a'); link.href = place.googleMapsURI; link.target = '_blank'; link.textContent = 'View Details on Google Maps'; content.appendChild(link); } // Display an info window. infoWindow.setHeaderContent(place.displayName); infoWindow.setContent(content); infoWindow.open({ anchor: marker, }); }
Map и Place были объявлены до этой функции:
const { Map } = await google.maps.importLibrary("maps"); const { Place } = await google.maps.importLibrary("places");