Как использовать Webpack с Google Maps ApiLoader для автозаполнения адреса?Javascript

Форум по Javascript
Ответить
Anonymous
 Как использовать Webpack с Google Maps ApiLoader для автозаполнения адреса?

Сообщение Anonymous »

Я пытаюсь интегрировать функцию Address 'Addrest' Address с использованием ApiLoader из библиотеки расширенных компонентов.
import { APILoader } from 'https://ajax.googleapis.com/ajax/libs/@ ... dex.min.js';
< /code>
Тем не менее, я хочу правильно интегрировать это в проект на основе Webpack, а не полагаться на CDN Imports. < /p>
Мой текущий код (на основе CDN ) < /p>
import {APILoader} from 'https://ajax.googleapis.com/ajax/libs/@ ... dex.min.js';

const CONFIGURATION = {
"ctaTitle": "Checkout",
"mapOptions": {"center":{"lat":37.4221,"lng":-122.0841},"fullscreenControl":true,"mapTypeControl":false,"streetViewControl":true,"zoom":11,"zoomControl":true,"maxZoom":22,"mapId":""},
"mapsApiKey": "",
"capabilities": {"addressAutocompleteControl":true,"mapDisplayControl":true,"ctaControl":true}
};

const SHORT_NAME_ADDRESS_COMPONENT_TYPES =
new Set(['street_number', 'administrative_area_level_1', 'postal_code']);

const ADDRESS_COMPONENT_TYPES_IN_FORM = [
'location',
'locality',
'administrative_area_level_1',
'postal_code',
'country',
];

function getFormInputElement(componentType) {
return document.getElementById(`${componentType}-input`);
}

function fillInAddress(place) {
function getComponentName(componentType) {
for (const component of place.address_components || []) {
if (component.types[0] === componentType) {
return SHORT_NAME_ADDRESS_COMPONENT_TYPES.has(componentType) ?
component.short_name :
component.long_name;
}
}
return '';
}

function getComponentText(componentType) {
return (componentType === 'location') ?
`${getComponentName('street_number')} ${getComponentName('route')}` :
getComponentName(componentType);
}

for (const componentType of ADDRESS_COMPONENT_TYPES_IN_FORM) {
getFormInputElement(componentType).value = getComponentText(componentType);
}
}

function renderAddress(place) {
const mapEl = document.querySelector('gmp-map');
const markerEl = document.querySelector('gmp-advanced-marker');

if (place.geometry && place.geometry.location) {
mapEl.center = place.geometry.location;
markerEl.position = place.geometry.location;
} else {
markerEl.position = null;
}
}

async function initMap() {
const {Autocomplete} = await APILoader.importLibrary('places');

const mapOptions = CONFIGURATION.mapOptions;
mapOptions.mapId = mapOptions.mapId || 'DEMO_MAP_ID';
mapOptions.center = mapOptions.center || {lat: 37.4221, lng: -122.0841};

await customElements.whenDefined('gmp-map');
document.querySelector('gmp-map').innerMap.setOptions(mapOptions);
const autocomplete = new Autocomplete(getFormInputElement('location'), {
fields: ['address_components', 'geometry', 'name'],
types: ['address'],
});

autocomplete.addListener('place_changed', () => {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert(`No details available for input: '${place.name}'`);
return;
}
renderAddress(place);
fillInAddress(place);
});
}

initMap();
< /code>
my webpack conf: < /p>
const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or subdirectory deploy
//.setManifestKeyPrefix('build/')

/*
* ENTRY CONFIG
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/app.js')
.addEntry('register', './assets/register.js')
.addEntry('address-selection', './assets/address_selection.js')

.copyFiles({
from: './assets/images',
to: 'images/[path][name].[ext]',
pattern: /\.(png|jpg|jpeg|svg|gif|webp|ico)$/
})

.copyFiles({
from: './assets/icons',
to: 'icons/[path][name].[ext]',
pattern: /\.(png|ico)$/
})

.copyFiles({
from: './assets',
to: 'site.webmanifest',
pattern: /site\.webmanifest$/
})

// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()

// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()

/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/fronten ... e-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())

// configure Babel
// .configureBabel((config) => {
// config.plugins.push('@babel/a-babel-plugin');
// })

// enables and configure @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = '3.38';
})

// enables Sass/SCSS support
.enableSassLoader()

//.addExternals()

// uncomment if you use TypeScript
//.enableTypeScriptLoader()

// uncomment if you use React
//.enableReactPreset()

// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())

// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();
< /code>
Как правильно настроить Webpack для использования ApiLoader? Нужно ли установить пакет через NPM, или есть альтернативный подход? Кроме того, как мне обработать вызовы импортибранции в WebPack?>

Подробнее здесь: https://stackoverflow.com/questions/794 ... tocomplete
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»