Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 92 additions & 120 deletions src/components/form/dt-location-map/dt-location-map-item.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { styleMap } from 'lit/directives/style-map.js';
import { classMap } from 'lit/directives/class-map.js';
import { msg } from '@lit/localize';
import DtBase from '../../dt-base.js';
import MapboxService from '../../../services/mapboxService.js';
import GoogleGeocodeService from '../../../services/googleGeocodeService.js';
import '../../icons/dt-icon.js';
import './dt-map-modal.js';

Expand Down Expand Up @@ -318,21 +316,6 @@ export default class DtLocationMapItem extends DtBase {
input.focus();
}
});

if (this.mapboxToken) {
this.mapboxService = new MapboxService(this.mapboxToken);
}
}

firstUpdated() {
// Only load Google Maps API for new/empty location items
if (this.googleToken && !this.metadata?.lat) {
this.googleGeocodeService = new GoogleGeocodeService(
this.googleToken,
window,
document,
);
}
}

disconnectedCallback() {
Expand Down Expand Up @@ -428,28 +411,41 @@ export default class DtLocationMapItem extends DtBase {
}

async _select(metadata) {
if (metadata.place_id && this.googleGeocodeService) {
// Google Places autocomplete will give a place_id instead of geometry details,
// so we need to get those details by geocoding the full address from Place lookup
this.saved = false;
this.loading = true;
const place = await this.googleGeocodeService.getPlaceDetails(
metadata,
this.locale,
);
this.loading = false;
if (place) {
if (place.error) {
console.error(place.error);
this.error = place.error.message;
return;
}
metadata.lat = place.lat;
metadata.lng = place.lng;
metadata.level = place.level;
}
}
this.saved = false;
this.loading = true;
this.dispatchEvent(
new CustomEvent('dt:geocode', {
bubbles: true,
composed: true,
detail: {
type: 'details',
suggestion: metadata,
locale: this.locale,
onSuccess: (place) => {
this.loading = false;

const updatedMetadata = { ...metadata };

if (place) {
updatedMetadata.lat = place.lat ?? metadata.lat;
updatedMetadata.lng = place.lng ?? metadata.lng;
updatedMetadata.level = place.level ?? metadata.level;
}

this._finalizeSelect(updatedMetadata);
},
onError: (error) => {
this.loading = false;
console.error(error);
this.error = error?.message || 'Error fetching location details';
this._finalizeSelect(metadata);
},
},
})
);
}

_finalizeSelect(metadata) {
// Create custom event with new/old values to pass to onchange function
const options = {
detail: {
Expand Down Expand Up @@ -541,58 +537,37 @@ export default class DtLocationMapItem extends DtBase {
}

/**
* Filter to options that:
* 1: are not selected
* 2: match the search query
* Filter to options that match the search query via injected geocoding
* @private
*/
async _filterOptions() {
if (this.query) {
if (this.googleToken && this.googleGeocodeService) {
this.saved = false;
this.loading = true;

try {
const predictions =
await this.googleGeocodeService.getPlacePredictions(
this.query,
this.locale,
);

this.filteredOptions = (predictions || []).map(i => ({
label: i.description,
place_id: i.place_id,
source: 'user',
raw: i,
}));

this.loading = false;
} catch (ex) {
console.error(ex);
this.error =
ex.message || 'An error occurred while searching for locations.';
this.loading = false;
return;
}
} else if (this.mapboxToken && this.mapboxService) {
this.saved = false;
this.loading = true;

const results = await this.mapboxService.searchPlaces(
this.query,
this.locale,
);

this.filteredOptions = results.map(i => ({
lng: i.center[0],
lat: i.center[1],
level: i.place_type[0],
label: i.place_name,
source: 'user',
}));

this.loading = false;
}
this.saved = false;
this.loading = true;

this.dispatchEvent(
new CustomEvent('dt:geocode', {
bubbles: true,
composed: true,
detail: {
type: 'search',
query: this.query,
locale: this.locale,
onSuccess: (results) => {
this.filteredOptions = results || [];
this.loading = false;
},
onError: (error) => {
console.error(error);
this.error =
error?.message || 'An error occurred while searching for locations.';
this.loading = false;
},
},
}),
);
} else {
this.filteredOptions = [];
}
return this.filteredOptions;
}
Expand Down Expand Up @@ -646,40 +621,37 @@ export default class DtLocationMapItem extends DtBase {
const { location } = e?.detail;
const { lat, lng } = location;

// reverse geocode location and save
if (this.googleGeocodeService) {
const results = await this.googleGeocodeService.reverseGeocode(
lng,
lat,
this.locale,
);
if (results && results.length) {
const place = results[0];
this._select({
lng: place.geometry.location.lng,
lat: place.geometry.location.lat,
level: place.types && place.types.length ? place.types[0] : null,
label: place.formatted_address,
source: 'user',
});
}
} else if (this.mapboxService) {
const results = await this.mapboxService.reverseGeocode(
lng,
lat,
this.locale,
);
if (results && results.length) {
const place = results[0];
this._select({
lng: place.center[0],
lat: place.center[1],
level: place.place_type[0],
label: place.place_name,
source: 'user',
});
}
}
this.saved = false;
this.loading = true;

this.dispatchEvent(
new CustomEvent('dt:geocode', {
bubbles: true,
composed: true,
detail: {
type: 'reverse',
lat,
lng,
locale: this.locale,
onSuccess: (place) => {
this.loading = false;
if (place) {
this._select({
lng: place.lng,
lat: place.lat,
level: place.level,
label: place.label,
source: place.source || 'user',
});
}
},
onError: (error) => {
this.loading = false;
console.error(error);
},
},
}),
);
}
}

Expand Down
110 changes: 110 additions & 0 deletions src/services/componentService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable no-unused-vars */
import ApiService from './apiService.js';
import MapboxService from './mapboxService.js';
import GoogleGeocodeService from './googleGeocodeService.js';

export default class ComponentService {
/**
Expand Down Expand Up @@ -54,6 +56,7 @@ export default class ComponentService {
'dt-button',
'dt-location',
'dt-users-connection',
'dt-location-map',
];
}

Expand Down Expand Up @@ -100,6 +103,22 @@ export default class ComponentService {
);
el.dataset.eventDtGetData = true;
}

if (!el.dataset.eventDtGeocode) {
el.addEventListener(
'dt:geocode',
this.handleGeocodeEvent.bind(this)
);
el.dataset.eventDtGeocode = true;
}

if (el.googleToken && !this.googleGeocodeService) {
this.googleGeocodeService = new GoogleGeocodeService(
el.googleToken,
window,
document,
);
}
Comment thread
cairocoder01 marked this conversation as resolved.
Outdated
});
}
}
Expand Down Expand Up @@ -260,6 +279,97 @@ export default class ComponentService {
}
}

/**
* Event listener for geocode events.
* Handles Mapbox and Google native API fallbacks.
* @param {Event} event
*/
async handleGeocodeEvent(event) {
const details = event.detail;
if (!details) return;

const { type, query, suggestion, lat, lng, locale, onSuccess, onError } = details;
const el = event.target; // This is the dt-location-map-item

try {
if (el.googleToken) {

if (type === 'search') {
const predictions = await this.googleGeocodeService.getPlacePredictions(query, locale);
const results = (predictions || []).map(i => ({
label: i.description,
place_id: i.place_id,
source: 'user',
raw: i,
}));
onSuccess(results);
}
else if (type === 'details') {
const place = await this.googleGeocodeService.getPlaceDetails(suggestion, locale);
if (place && place.error) throw new Error(place.error.message);

onSuccess({
...suggestion,
lat: place?.lat,
lng: place?.lng,
level: place?.level
});
}
else if (type === 'reverse') {
const results = await this.googleGeocodeService.reverseGeocode(lng, lat, locale);
if (results && results.length) {
const place = results[0];
onSuccess({
lng: place.geometry.location.lng,
lat: place.geometry.location.lat,
level: place.types && place.types.length ? place.types[0] : null,
label: place.formatted_address,
source: 'user',
});
} else {
onSuccess(null);
}
}
}

else if (el.mapboxToken) {
const mapboxService = new MapboxService(el.mapboxToken);

if (type === 'search') {
const results = await mapboxService.searchPlaces(query, locale);
const formatted = results.map(i => ({
lng: i.center[0],
lat: i.center[1],
level: i.place_type[0],
label: i.place_name,
source: 'user',
}));
onSuccess(formatted);
}
else if (type === 'details') {
onSuccess(suggestion);
}
else if (type === 'reverse') {
const results = await mapboxService.reverseGeocode(lng, lat, locale);
if (results && results.length) {
const place = results[0];
onSuccess({
lng: place.center[0],
lat: place.center[1],
level: place.place_type[0],
label: place.place_name,
source: 'user',
});
} else {
onSuccess(null);
}
}
}
} catch (ex) {
if (onError) onError(ex);
}
}

/**
* Event listener for change events.
* Will set loading property, attempt to save value via API,
Expand Down
Loading