diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f90eda7c..418861d5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,3 +27,4 @@ jobs: ${{ runner.os }}-node - run: npm i - run: npm run test:check + - run: npm run lint diff --git a/eslint.config.mjs b/eslint.config.mjs index 667eb74a..d2b687c7 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -33,9 +33,13 @@ export default [ node: true, }, rules: { - "no-unused-vars": [1, { varsIgnorePattern: "init*" }], + // The TS rule replaces the base one under @typescript-eslint/recommended, + // so the initMap-style callback exemption has to live on it. + "no-unused-vars": 0, + "@typescript-eslint/no-unused-vars": [2, { varsIgnorePattern: "^init" }], "no-var": 2, - "@typescript-eslint/no-var-requires": 0, + // The build scripts are CommonJS (typescript-eslint v8 renamed no-var-requires). + "@typescript-eslint/no-require-imports": 0, "prefer-arrow-callback": 2, }, }), diff --git a/package-lock.json b/package-lock.json index 14231508..0967e530 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,7 +20,7 @@ "@playwright/test": "^1.60.0", "@types/geojson": "^7946.0.16", "@types/supercluster": "^7.1.3", - "@types/woosmap.map": "^1.4.26", + "@types/woosmap.map": "^1.4.28", "@typescript-eslint/eslint-plugin": "^8.60.1", "@typescript-eslint/parser": "^8.15.0", "chalk": "^5.6.2", @@ -2753,9 +2753,9 @@ } }, "node_modules/@types/woosmap.map": { - "version": "1.4.26", - "resolved": "https://registry.npmjs.org/@types/woosmap.map/-/woosmap.map-1.4.26.tgz", - "integrity": "sha512-n5Sg3ZoVORSMG7PpSll0QZYYrLFAmeOvaxWg1Q2CKDodU4XUCecONRkZpEdQK2fMu0qqpSCvYR/ZfXQVH/ZhYg==", + "version": "1.4.28", + "resolved": "https://registry.npmjs.org/@types/woosmap.map/-/woosmap.map-1.4.28.tgz", + "integrity": "sha512-BeO7QMvkoeqA/B+YGoVeoPAiqwBwpCd9pAybSqRSlYqgsxwkt6jMWQgaY5VfOstVExQ2NfX9XPyJpE6fAccMzg==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 05e6372a..880a97b5 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "@playwright/test": "^1.60.0", "@types/geojson": "^7946.0.16", "@types/supercluster": "^7.1.3", - "@types/woosmap.map": "^1.4.26", + "@types/woosmap.map": "^1.4.28", "@typescript-eslint/eslint-plugin": "^8.60.1", "@typescript-eslint/parser": "^8.15.0", "chalk": "^5.6.2", diff --git a/samples/add-map/add-map.json b/samples/add-map/add-map.json index 89a92bbd..b9093899 100644 --- a/samples/add-map/add-map.json +++ b/samples/add-map/add-map.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/add-map/index.njk b/samples/add-map/index.njk index 8e3f95a0..a9b6bb9a 100644 --- a/samples/add-map/index.njk +++ b/samples/add-map/index.njk @@ -2,6 +2,6 @@ {% block html %} -
+ {% endblock %} diff --git a/samples/add-map/index.ts b/samples/add-map/index.ts index 64d12dc7..7ce19592 100644 --- a/samples/add-map/index.ts +++ b/samples/add-map/index.ts @@ -2,7 +2,9 @@ // Initialize and add the map let map: woosmap.map.Map; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + // [START woosmap_add_map_instantiate_map] // The location of London const position: woosmap.map.LatLngLiteral = { @@ -11,19 +13,15 @@ function initMap(): void { }; // The map, centered at London - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 13, center: position, }); // [END woosmap_add_map_instantiate_map] } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_add_map] export {}; diff --git a/samples/datasets-api/datasets-api.json b/samples/datasets-api/datasets-api.json index 99116756..128002bf 100644 --- a/samples/datasets-api/datasets-api.json +++ b/samples/datasets-api/datasets-api.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/datasets-api/index.njk b/samples/datasets-api/index.njk index 7581601e..b4fac2c5 100644 --- a/samples/datasets-api/index.njk +++ b/samples/datasets-api/index.njk @@ -38,7 +38,7 @@
-
+
{% svgIcon 'search.svg' %} Promise; +let debouncedLocalitiesAutocomplete: ( + request: woosmap.map.localities.LocalitiesAutocompleteRequest, +) => Promise; let results: HTMLOListElement; let resetButton: HTMLButtonElement; const datasetId = "a01df3d6-fe7d-42df-8fee-9f31726a2641"; //US - Seismic Hazard Map -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("drawing"); + // [START woosmap_datasets_api_instantiate_map] - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ gestureHandling: "auto", defaultStyle: "streets", }); @@ -41,7 +47,7 @@ function initServices(): void { datasetsService = new woosmap.map.DatasetsService(datasetId); datasetsOverlay.setMap(map); - localitiesService = new window.woosmap.map.LocalitiesService(); + localitiesService = new woosmap.map.LocalitiesService(); request = { input: "", types: ["locality", "address", "postal_code"], @@ -60,7 +66,7 @@ function initDrawing(): void { }, }); drawTools.addControl(map); - drawTools.addListener("draw.create", async (ev) => { + drawTools.addListener("draw.create", async () => { const collection = drawTools.getAll(); if (collection.features.length > 1) { for (const feature of collection.features.slice(0, -1)) { @@ -210,7 +216,7 @@ function manageFiltersElements() { const selectElement = event.target as HTMLSelectElement; updateDataset(selectElement.value); }); - operatorSelect.addEventListener("change", async (ev) => { + operatorSelect.addEventListener("change", async () => { const collection = drawTools.getAll(); await intersectCb(collection); }); @@ -245,16 +251,16 @@ async function intersectCb(ev) { await applyOperator(ev.features[0].geometry, operatorSelect.value) .then((response) => { - const features = []; + const features: woosmap.map.GeoJSONFeature[] = []; bindResultsToPanel(response.features); map.data.forEach((feature) => { map.data.remove(feature); }); for (const feature of response.features) { - // @ts-ignore TypeDef to be updated features.push({ type: "Feature", geometry: feature.geometry, + properties: {}, }); } @@ -282,8 +288,8 @@ function bindResultsToPanel(features: woosmap.map.GeoJSONFeature[]) { resultListItem.innerHTML + `${key} ${attributes[key]}`; } - }), - results.appendChild(resultListItem); + }); + results.appendChild(resultListItem); }); } else { results.innerHTML = "No results found"; @@ -291,19 +297,19 @@ function bindResultsToPanel(features: woosmap.map.GeoJSONFeature[]) { } } // [START woosmap_localities_autocomplete_debounce_promise] -let PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +let PRESERVE_COMMENT_ABOVE; // eslint-disable-line no-unassigned-vars -- force tsc to maintain the comment above -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -330,14 +336,9 @@ function debouncePromise( } // [END woosmap_localities_autocomplete_debounce_promise] */ -PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +PRESERVE_COMMENT_ABOVE; // eslint-disable-line @typescript-eslint/no-unused-expressions -- force tsc to maintain the comment above -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_datasets_api] export {}; diff --git a/samples/directions-advanced/directions-advanced.json b/samples/directions-advanced/directions-advanced.json index 6edde3f9..11c877f1 100644 --- a/samples/directions-advanced/directions-advanced.json +++ b/samples/directions-advanced/directions-advanced.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/directions-advanced/index.njk b/samples/directions-advanced/index.njk index abc6d73f..28884b06 100644 --- a/samples/directions-advanced/index.njk +++ b/samples/directions-advanced/index.njk @@ -200,7 +200,7 @@
-
+
Drag markers to update route
diff --git a/samples/directions-advanced/index.ts b/samples/directions-advanced/index.ts index 9495c0d9..8db2e424 100644 --- a/samples/directions-advanced/index.ts +++ b/samples/directions-advanced/index.ts @@ -3,7 +3,7 @@ let map: woosmap.map.Map; let bounds: woosmap.map.LatLngBounds; let directionsService: woosmap.map.DirectionsService; let directionsRequest: woosmap.map.DirectionRequest; -let markersArray: woosmap.map.Marker[] = []; +let markersArray: woosmap.map.marker.AdvancedMarkerElement[] = []; let waypointsList: HTMLElement; let originContainer: HTMLElement; let destinationContainer: HTMLElement; @@ -18,24 +18,15 @@ const travelModeIcons = { function createMarker( position: woosmap.map.LatLngLiteral | woosmap.map.LatLng, label: string, - url: string, -): woosmap.map.Marker { - return new woosmap.map.Marker({ + background: string, +): woosmap.map.marker.AdvancedMarkerElement { + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ background, glyphText: label, glyphColor: "#FFFFFF" }); + return new woosmap.map.marker.AdvancedMarkerElement({ map, position, - draggable: true, - icon: { - url, - labelOrigin: new woosmap.map.Point(13, 15), - scaledSize: { - height: 38, - width: 26, - }, - }, - label: { - text: label, - color: "white", - }, + gmpDraggable: true, + content: pin.element, }); } @@ -48,26 +39,18 @@ function clearMarkers(): void { function displayDirectionsMarkers(): void { clearMarkers(); - const originMarker = createMarker( - directionsRequest.origin, - "O", - "https://images.woosmap.com/marker-blue.svg", - ); + const originMarker = createMarker(directionsRequest.origin, "O", "#3d5afe"); originMarker.addListener("dragend", () => { - directionsRequest.origin = originMarker.getPosition(); - setLatLngToContainer(originContainer, originMarker.getPosition().toJSON()); + directionsRequest.origin = originMarker.position!; + setLatLngToContainer(originContainer, originMarker.position!.toJSON()); calculateDirections(); }); - const destinationMarker = createMarker( - directionsRequest.destination, - "D", - "https://images.woosmap.com/marker-red.svg", - ); + const destinationMarker = createMarker(directionsRequest.destination, "D", "#f50057"); destinationMarker.addListener("dragend", () => { - directionsRequest.destination = destinationMarker.getPosition(); + directionsRequest.destination = destinationMarker.position!; setLatLngToContainer( destinationContainer, - destinationMarker.getPosition().toJSON(), + destinationMarker.position!.toJSON(), ); calculateDirections(); }); @@ -80,12 +63,12 @@ function displayDirectionsMarkers(): void { const waypointMarker = createMarker( waypoint.location as woosmap.map.LatLngLiteral, (index + 1).toString(), - "https://images.woosmap.com/marker-green.svg", + "#03BDA5", ); waypointMarker.addListener("dragend", () => { - waypoints[index].location = waypointMarker.getPosition().toJSON(); + waypoints[index].location = waypointMarker.position!.toJSON(); waypointsList.querySelectorAll("li")[index].innerHTML = - `lat: ${waypointMarker.getPosition().lat().toFixed(4)}, lng: ${waypointMarker.getPosition().lng().toFixed(4)}`; + `lat: ${waypointMarker.position!.lat().toFixed(4)}, lng: ${waypointMarker.position!.lng().toFixed(4)}`; calculateDirections(); }); markersArray.push(waypointMarker); @@ -522,8 +505,12 @@ function initUI(): void { ); } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.5074, lng: -0.1478 }, zoom: 10, }); @@ -539,12 +526,7 @@ function initMap(): void { calculateDirections(); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_directions_advanced] export {}; diff --git a/samples/directions-simple/directions-simple.json b/samples/directions-simple/directions-simple.json index f49c2d03..13f648bb 100644 --- a/samples/directions-simple/directions-simple.json +++ b/samples/directions-simple/directions-simple.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/directions-simple/index.njk b/samples/directions-simple/index.njk index 9acc3844..de2829b0 100644 --- a/samples/directions-simple/index.njk +++ b/samples/directions-simple/index.njk @@ -81,5 +81,5 @@
-
+ {% endblock %} diff --git a/samples/directions-simple/index.ts b/samples/directions-simple/index.ts index d4f47aa6..295f2e7a 100644 --- a/samples/directions-simple/index.ts +++ b/samples/directions-simple/index.ts @@ -3,10 +3,13 @@ let map: woosmap.map.Map; let fromSelect: HTMLSelectElement; let toSelect: HTMLSelectElement; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const directionsService = new woosmap.map.DirectionsService(); const directionsRenderer = new woosmap.map.DirectionsRenderer({}); - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 7, center: { lat: 43.5, @@ -76,12 +79,7 @@ function getSelectedLatLng( }; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_directions_simple] export {}; diff --git a/samples/distance-isochrone/distance-isochrone.json b/samples/distance-isochrone/distance-isochrone.json index 8f9c29db..c115b9d3 100644 --- a/samples/distance-isochrone/distance-isochrone.json +++ b/samples/distance-isochrone/distance-isochrone.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/distance-isochrone/index.njk b/samples/distance-isochrone/index.njk index 8a5da851..2c1a9df9 100644 --- a/samples/distance-isochrone/index.njk +++ b/samples/distance-isochrone/index.njk @@ -34,7 +34,7 @@ > -
+ {% endblock %} diff --git a/samples/distance-isochrone/index.ts b/samples/distance-isochrone/index.ts index ee512c1d..304bcb22 100644 --- a/samples/distance-isochrone/index.ts +++ b/samples/distance-isochrone/index.ts @@ -2,51 +2,47 @@ let map: woosmap.map.Map; let methodSelect, modeSelect: HTMLSelectElement; let distanceInput: HTMLInputElement; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; let polyline: woosmap.map.Polyline; let distanceService: woosmap.map.DistanceService; -const markerIcon: woosmap.map.Icon = { - url: "https://images.woosmap.com/icons/pin-red.png", - scaledSize: { - height: 38, - width: 26, - }, -}; const centerLatLng: woosmap.map.LatLngLiteral = { lat: 51.5, lng: -0.234, }; +function createMarkerContent(): HTMLElement { + return new woosmap.map.marker.PinElement().element; +} function createMarker( position: woosmap.map.LatLngLiteral, - icon: woosmap.map.Icon, map: woosmap.map.Map, ) { - const marker = new window.woosmap.map.Marker({ + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position, - icon, + content: createMarkerContent(), }); marker.setMap(map); return marker; } -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 9, - center: centerLatLng, - }, - ); +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ + zoom: 9, + center: centerLatLng, + }); distanceService = new woosmap.map.DistanceService(); - marker = createMarker(centerLatLng, markerIcon, map); + marker = createMarker(centerLatLng, map); map.addListener("click", (e) => { marker.setMap(null); - marker = createMarker(e.latlng, markerIcon, map); + marker = createMarker(e.latlng, map); computeIsochrone(e.latlng); }); const onChangeHandler = () => { - computeIsochrone(marker.getPosition().toJSON()); + computeIsochrone(marker.position!.toJSON()); }; methodSelect = document.getElementById( "isochrone-method-select", @@ -116,12 +112,7 @@ function fitToCoordinates( } } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_distance_isochrone] export {}; diff --git a/samples/distance-matrix-advanced/distance-matrix-advanced.json b/samples/distance-matrix-advanced/distance-matrix-advanced.json index c02a8e79..29b5ff95 100644 --- a/samples/distance-matrix-advanced/distance-matrix-advanced.json +++ b/samples/distance-matrix-advanced/distance-matrix-advanced.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/distance-matrix-advanced/index.njk b/samples/distance-matrix-advanced/index.njk index 6b63ffda..c6571f6e 100644 --- a/samples/distance-matrix-advanced/index.njk +++ b/samples/distance-matrix-advanced/index.njk @@ -168,7 +168,7 @@
-
+
diff --git a/samples/distance-matrix-advanced/index.ts b/samples/distance-matrix-advanced/index.ts index f1ae83c9..a6267275 100644 --- a/samples/distance-matrix-advanced/index.ts +++ b/samples/distance-matrix-advanced/index.ts @@ -3,7 +3,7 @@ let map: woosmap.map.Map; let bounds: woosmap.map.LatLngBounds; let distanceService: woosmap.map.DistanceService; let distanceRequest: woosmap.map.distance.DistanceMatrixRequest; -let markersArray: woosmap.map.Marker[] = []; +let markersArray: woosmap.map.marker.AdvancedMarkerElement[] = []; let originsList: HTMLElement; let destinationsList: HTMLElement; const origins: woosmap.map.LatLngLiteral[] = []; @@ -13,23 +13,14 @@ let line: woosmap.map.Polyline | null = null; function createMarker( position: woosmap.map.LatLngLiteral, label: string, - url: string, -): woosmap.map.Marker { - return new woosmap.map.Marker({ + background: string, +): woosmap.map.marker.AdvancedMarkerElement { + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ background, glyphText: label, glyphColor: "#FFFFFF" }); + return new woosmap.map.marker.AdvancedMarkerElement({ map, position, - icon: { - url, - labelOrigin: new woosmap.map.Point(13, 15), - scaledSize: { - height: 38, - width: 26, - }, - }, - label: { - text: label, - color: "white", - }, + content: pin.element, }); } @@ -48,22 +39,14 @@ function displayMatrixMarkers( origins.forEach((origin, index) => { bounds.extend(origin); markersArray.push( - createMarker( - origin, - (index + 1).toString(), - "https://images.woosmap.com/marker-blue.svg", - ), + createMarker(origin, (index + 1).toString(), "#3d5afe"), ); }); destinations.forEach((destination, index) => { bounds.extend(destination); markersArray.push( - createMarker( - destination, - (index + 1).toString(), - "https://images.woosmap.com/marker-red.svg", - ), + createMarker(destination, (index + 1).toString(), "#f50057"), ); }); @@ -407,8 +390,12 @@ function initUI(): void { registerAddButton(".addLocation__origins", originsList, origins); } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.4855, lng: -0.3179 }, zoom: 6, }); @@ -419,12 +406,7 @@ function initMap(): void { calculateDistances(); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_distance_matrix_advanced] export {}; diff --git a/samples/distance-matrix/distance-matrix.json b/samples/distance-matrix/distance-matrix.json index 724a92f0..91eb2350 100644 --- a/samples/distance-matrix/distance-matrix.json +++ b/samples/distance-matrix/distance-matrix.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/distance-matrix/index.njk b/samples/distance-matrix/index.njk index e114c117..ab8eed77 100644 --- a/samples/distance-matrix/index.njk +++ b/samples/distance-matrix/index.njk @@ -2,7 +2,7 @@ {% block html %}
-
+

Request

diff --git a/samples/distance-matrix/index.ts b/samples/distance-matrix/index.ts index f18c265c..73446a85 100644 --- a/samples/distance-matrix/index.ts +++ b/samples/distance-matrix/index.ts @@ -3,28 +3,19 @@ let map: woosmap.map.Map; let bounds: woosmap.map.LatLngBounds; let distanceService: woosmap.map.DistanceService; let distanceRequest: woosmap.map.distance.DistanceMatrixRequest; -const markersArray: woosmap.map.Marker[] = []; +const markersArray: woosmap.map.marker.AdvancedMarkerElement[] = []; function createMarker( position: woosmap.map.LatLng, label: string, - url: string, -): woosmap.map.Marker { - return new woosmap.map.Marker({ + background: string, +): woosmap.map.marker.AdvancedMarkerElement { + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ background, glyphText: label, glyphColor: "#FFFFFF" }); + return new woosmap.map.marker.AdvancedMarkerElement({ map, position, - icon: { - url, - labelOrigin: new woosmap.map.Point(14, 15), - scaledSize: { - height: 38, - width: 26, - }, - }, - label: { - text: label, - color: "white", - }, + content: pin.element, }); } @@ -35,18 +26,14 @@ function fitBoundsToMatrix( origins.forEach((origin) => { bounds.extend(origin); markersArray.push( - createMarker(origin, "O", "https://images.woosmap.com/marker-blue.svg"), + createMarker(origin, "O", "#3d5afe"), ); }); destinations.forEach((destination) => { bounds.extend(destination); markersArray.push( - createMarker( - destination, - "D", - "https://images.woosmap.com/marker-red.svg", - ), + createMarker(destination, "D", "#f50057"), ); }); @@ -91,8 +78,12 @@ function calculateDistances(): void { } } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 45.53, lng: 2.4 }, zoom: 10, }); @@ -101,12 +92,7 @@ function initMap(): void { calculateDistances(); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_distance_matrix] export {}; diff --git a/samples/draw-shapes-events/draw-shapes-events.json b/samples/draw-shapes-events/draw-shapes-events.json index 721ab647..8b239aed 100644 --- a/samples/draw-shapes-events/draw-shapes-events.json +++ b/samples/draw-shapes-events/draw-shapes-events.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/draw-shapes-events/index.njk b/samples/draw-shapes-events/index.njk index 0fc3a07e..51b536e4 100644 --- a/samples/draw-shapes-events/index.njk +++ b/samples/draw-shapes-events/index.njk @@ -1,7 +1,7 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
-
+
{% endblock %} diff --git a/samples/draw-shapes-events/index.ts b/samples/draw-shapes-events/index.ts index 4d813e28..18d98cd2 100644 --- a/samples/draw-shapes-events/index.ts +++ b/samples/draw-shapes-events/index.ts @@ -77,19 +77,20 @@ function setupListener(name) { } } -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("drawing"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 31.54350013250679, lng: -97.13238669872247 }, zoom: 6.5, - }, - ); + }); - const draw = new window.woosmap.map.Drawing({}); + const draw = new woosmap.map.Drawing({}); draw.addControl(map); - window.woosmap.map.event.addListenerOnce(map, "idle", () => { + woosmap.map.event.addListenerOnce(map, "idle", () => { draw.add(data); }); @@ -103,12 +104,7 @@ function initMap() { } } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_draw_shapes_events] export {}; diff --git a/samples/draw-shapes/draw-shapes.json b/samples/draw-shapes/draw-shapes.json index 2ad563f4..f076b39d 100644 --- a/samples/draw-shapes/draw-shapes.json +++ b/samples/draw-shapes/draw-shapes.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/draw-shapes/index.njk b/samples/draw-shapes/index.njk index cf2aa425..f1217c33 100644 --- a/samples/draw-shapes/index.njk +++ b/samples/draw-shapes/index.njk @@ -6,7 +6,7 @@
-
+ -
+
{% endblock %} diff --git a/samples/geolocation-api/index.ts b/samples/geolocation-api/index.ts index 6bdcfd10..67f652dc 100644 --- a/samples/geolocation-api/index.ts +++ b/samples/geolocation-api/index.ts @@ -21,7 +21,10 @@ interface Bounds { southwest: woosmap.map.LatLngLiteral; } -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + fetch(`https://api.woosmap.com/geolocation/position/?key=${woosmap_key}`) .then((result) => { return result.json(); @@ -51,10 +54,13 @@ function renderUserLocationOnMap({ latitude, accuracy, longitude, viewport }) { } else if (accuracy > 1) { zoom = 11; } - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - center: userPosition, + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ zoom, }); + map.moveCamera({ + center: userPosition, + }); if (viewport) { const bounds = { east: viewport.northeast.lng, @@ -65,11 +71,12 @@ function renderUserLocationOnMap({ latitude, accuracy, longitude, viewport }) { map.fitBounds(bounds); plotBoundary(bounds); } - const marker = new woosmap.map.Marker({ + const markerContent = document.createElement("img"); + markerContent.src = "https://images.woosmap.com/user-position-small.png"; + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: userPosition, - icon: { - url: "https://images.woosmap.com/user-position-small.png", - }, + content: markerContent, }); marker.setMap(map); } @@ -124,12 +131,7 @@ function plotBoundary(bounds: woosmap.map.LatLngBoundsLiteral): void { rectangle.setMap(map); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_geolocation_api] export {}; diff --git a/samples/indoor-directions-service/index.njk b/samples/indoor-directions-service/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-directions-service/index.njk +++ b/samples/indoor-directions-service/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-directions-service/index.ts b/samples/indoor-directions-service/index.ts index a3566ed0..9c151221 100644 --- a/samples/indoor-directions-service/index.ts +++ b/samples/indoor-directions-service/index.ts @@ -4,22 +4,22 @@ let indoorDirectionsRequest: woosmap.map.IndoorDirectionRequest; let indoorRenderer: woosmap.map.IndoorRenderer; let venue: string; -function initMap() { +async function initMap() { + await woosmap.map.importLibrary("maps"); + venue = "gdn_doc"; - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 43.6066, lng: 3.9218 }, zoom: 19.5, - }, - ); + }); indoorRenderer = new woosmap.map.IndoorRenderer({ venue: venue, }); const indoorService: woosmap.map.IndoorService = - new window.woosmap.map.IndoorService(); + new woosmap.map.IndoorService(); // Indoor event that is triggered when the indoor venue is loaded. indoorRenderer.addListener( "indoor_venue_loaded", @@ -56,12 +56,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_directions_service] export {}; diff --git a/samples/indoor-directions-service/indoor-directions-service.json b/samples/indoor-directions-service/indoor-directions-service.json index 1fa40200..1fa6719c 100644 --- a/samples/indoor-directions-service/indoor-directions-service.json +++ b/samples/indoor-directions-service/indoor-directions-service.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/indoor-map-advanced/index.njk b/samples/indoor-map-advanced/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-map-advanced/index.njk +++ b/samples/indoor-map-advanced/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-map-advanced/index.ts b/samples/indoor-map-advanced/index.ts index 69ee79b4..e8c0c0f7 100644 --- a/samples/indoor-map-advanced/index.ts +++ b/samples/indoor-map-advanced/index.ts @@ -1,14 +1,14 @@ // [START woosmap_indoor_map_advanced] let map: woosmap.map.Map; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 43.6066, lng: 3.9218 }, zoom: 19.5, - }, - ); + }); const indoorRenderer = new woosmap.map.IndoorRenderer({ venue: "wgs_doc", @@ -32,12 +32,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_map_advanced] export {}; diff --git a/samples/indoor-map-advanced/indoor-map-advanced.json b/samples/indoor-map-advanced/indoor-map-advanced.json index d418830a..3d6896fd 100644 --- a/samples/indoor-map-advanced/indoor-map-advanced.json +++ b/samples/indoor-map-advanced/indoor-map-advanced.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/indoor-map-simple/index.njk b/samples/indoor-map-simple/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-map-simple/index.njk +++ b/samples/indoor-map-simple/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-map-simple/index.ts b/samples/indoor-map-simple/index.ts index 7493235c..91799788 100644 --- a/samples/indoor-map-simple/index.ts +++ b/samples/indoor-map-simple/index.ts @@ -1,14 +1,14 @@ // [START woosmap_indoor_map_simple] let map: woosmap.map.Map; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 43.6066, lng: 3.9218 }, zoom: 19.5, - }, - ); + }); const indoorRenderer = new woosmap.map.IndoorRenderer({ venue: "wgs_doc", @@ -30,12 +30,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_map_simple] export {}; diff --git a/samples/indoor-map-simple/indoor-map-simple.json b/samples/indoor-map-simple/indoor-map-simple.json index 538ca712..d89d5bc3 100644 --- a/samples/indoor-map-simple/indoor-map-simple.json +++ b/samples/indoor-map-simple/indoor-map-simple.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/indoor-navigation-widget/index.njk b/samples/indoor-navigation-widget/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-navigation-widget/index.njk +++ b/samples/indoor-navigation-widget/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-navigation-widget/index.ts b/samples/indoor-navigation-widget/index.ts index 84a78952..e44500a5 100644 --- a/samples/indoor-navigation-widget/index.ts +++ b/samples/indoor-navigation-widget/index.ts @@ -5,12 +5,14 @@ let indoorNavigation: woosmap.map.NavigationWidget; let indoorService: woosmap.map.IndoorService; let venue: string; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + venue = "gdn_doc"; - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { center: { lat: 43.6066, lng: 3.9218 } }, - ); + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ + center: { lat: 43.6066, lng: 3.9218 }, + }); const conf: woosmap.map.IndoorRendererOptions = { venue: venue, @@ -22,14 +24,14 @@ function initMap(): void { indoorRenderer.setMap(map); // Indoor event that is triggered when the indoor venue is loaded. - indoorRenderer.addListener("indoor_venue_loaded", (venue) => { - indoorService = new window.woosmap.map.IndoorService(); + indoorRenderer.addListener("indoor_venue_loaded", () => { + indoorService = new woosmap.map.IndoorService(); const request: woosmap.map.IndoorDirectionRequest = { venueId: "gdn_doc", - origin: new window.woosmap.map.LatLng(48.8801287, 2.3548678), + origin: new woosmap.map.LatLng(48.8801287, 2.3548678), originLevel: 0, - destination: new window.woosmap.map.LatLng(48.8799341, 2.3563779), + destination: new woosmap.map.LatLng(48.8799341, 2.3563779), destinationLevel: 0, units: "metric", originId: null, @@ -38,7 +40,7 @@ function initMap(): void { indoorService.directions(request, (response) => { if (response) { indoorRenderer.setDirections(response); - indoorNavigation = new window.woosmap.map.NavigationWidget( + indoorNavigation = new woosmap.map.NavigationWidget( indoorRenderer, exitNavigation, ); @@ -58,12 +60,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_navigation_widget] export {}; diff --git a/samples/indoor-navigation-widget/indoor-navigation-widget.json b/samples/indoor-navigation-widget/indoor-navigation-widget.json index 2bbd777c..d1d7cadd 100644 --- a/samples/indoor-navigation-widget/indoor-navigation-widget.json +++ b/samples/indoor-navigation-widget/indoor-navigation-widget.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/indoor-widget-advanced/index.njk b/samples/indoor-widget-advanced/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-widget-advanced/index.njk +++ b/samples/indoor-widget-advanced/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-widget-advanced/index.ts b/samples/indoor-widget-advanced/index.ts index 05ac8754..2bfbe5ee 100644 --- a/samples/indoor-widget-advanced/index.ts +++ b/samples/indoor-widget-advanced/index.ts @@ -1,14 +1,14 @@ // [START woosmap_indoor_widget_advanced] let map: woosmap.map.Map; -function initMap(): void { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 43.6066, lng: 3.9218 }, zoom: 5, - }, - ); + }); const conf: woosmap.map.IndoorRendererOptions = { centerMap: false, @@ -48,12 +48,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_widget_advanced] export {}; diff --git a/samples/indoor-widget-advanced/indoor-widget-advanced.json b/samples/indoor-widget-advanced/indoor-widget-advanced.json index 8fbbdacd..7fae9dc7 100644 --- a/samples/indoor-widget-advanced/indoor-widget-advanced.json +++ b/samples/indoor-widget-advanced/indoor-widget-advanced.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/indoor-widget-simple/index.njk b/samples/indoor-widget-simple/index.njk index d261b50e..a99bcaec 100644 --- a/samples/indoor-widget-simple/index.njk +++ b/samples/indoor-widget-simple/index.njk @@ -6,7 +6,7 @@
-
+ {% endblock %} diff --git a/samples/indoor-widget-simple/index.ts b/samples/indoor-widget-simple/index.ts index 48419588..952a4c8d 100644 --- a/samples/indoor-widget-simple/index.ts +++ b/samples/indoor-widget-simple/index.ts @@ -1,12 +1,11 @@ // [START woosmap_indoor_widget_simple] let map: woosmap.map.Map; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + console.log("init map"); - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - {}, - ); + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; const conf: woosmap.map.IndoorRendererOptions = { defaultFloor: 0, //Render map with default floor @@ -51,12 +50,7 @@ const hideLoader = () => { (document.querySelector(".progress") as HTMLElement).remove(); }; -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_indoor_widget_simple] export {}; diff --git a/samples/indoor-widget-simple/indoor-widget-simple.json b/samples/indoor-widget-simple/indoor-widget-simple.json index 502eb70b..b9edec73 100644 --- a/samples/indoor-widget-simple/indoor-widget-simple.json +++ b/samples/indoor-widget-simple/indoor-widget-simple.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/infowindow-simple/index.njk b/samples/infowindow-simple/index.njk index f2ff4535..6150b04a 100644 --- a/samples/infowindow-simple/index.njk +++ b/samples/infowindow-simple/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
+ {% endblock %} diff --git a/samples/infowindow-simple/index.ts b/samples/infowindow-simple/index.ts index 9f17b284..d9fdd458 100644 --- a/samples/infowindow-simple/index.ts +++ b/samples/infowindow-simple/index.ts @@ -2,18 +2,19 @@ // This example displays a marker at the center of London. // When the user clicks the marker, an info window opens. -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + // The map, centered at London - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 10, center: { lat: 51.57, lng: -0.13, }, - }, - ); + }); const londonInfoWindowHTML = "
" + @@ -22,35 +23,32 @@ function initMap(): void { "

London is the capital and largest city of England and the United Kingdom. Wikipedia →

" + "
"; - const marker = new window.woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: { lat: 51.515, lng: -0.13, }, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, + gmpClickable: true, map, }); const infoWindow = new woosmap.map.InfoWindow({}); infoWindow.setOffset(new woosmap.map.Point(0, -50)); infoWindow.setContent(londonInfoWindowHTML); - infoWindow.open(map, marker.position); + infoWindow.open({map, anchor: marker}); marker.addListener("click", () => { - infoWindow.open(map, marker.getPosition()); + infoWindow.open({map, anchor: marker}); }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_infowindow_simple] export {}; diff --git a/samples/infowindow-simple/infowindow-simple.json b/samples/infowindow-simple/infowindow-simple.json index 57b6c7f2..157e6da6 100644 --- a/samples/infowindow-simple/infowindow-simple.json +++ b/samples/infowindow-simple/infowindow-simple.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-api-autocomplete-advanced/index.ts b/samples/localities-api-autocomplete-advanced/index.ts index 473ce870..a8f07a32 100644 --- a/samples/localities-api-autocomplete-advanced/index.ts +++ b/samples/localities-api-autocomplete-advanced/index.ts @@ -1,9 +1,7 @@ // [START woosmap_localities_api_autocomplete_advanced] const componentsRestriction = []; const woosmap_key = "YOUR_API_KEY"; -let debouncedAutocomplete: ( - ...args: any[] -) => Promise; +let debouncedAutocomplete: typeof autocompleteAddress; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; @@ -80,7 +78,7 @@ function formatPredictionList(locality): string { const prediction = locality; const predictionClass = "no-viewpoint"; const matched_substrings = prediction.matched_substrings; - let formatted_name = ""; + let formatted_name: string; if ( prediction.matched_substrings && prediction.matched_substrings.description @@ -161,17 +159,17 @@ function buildQueryString(params: object) { return queryStringParts.join("&"); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { diff --git a/samples/localities-api-autocomplete/index.ts b/samples/localities-api-autocomplete/index.ts index 9c74ef42..319e5588 100644 --- a/samples/localities-api-autocomplete/index.ts +++ b/samples/localities-api-autocomplete/index.ts @@ -1,9 +1,7 @@ // [START woosmap_localities_api_autocomplete] const componentsRestriction = []; const woosmap_key = "YOUR_API_KEY"; -let debouncedAutocomplete: ( - ...args: any[] -) => Promise; +let debouncedAutocomplete: typeof autocompleteAddress; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; @@ -81,7 +79,7 @@ function formatPredictionList(locality): string { const prediction = locality; const predictionClass = "no-viewpoint"; const matched_substrings = prediction.matched_substrings; - let formatted_name = ""; + let formatted_name: string; if ( prediction.matched_substrings && prediction.matched_substrings.description @@ -161,17 +159,17 @@ function buildQueryString(params: object) { return queryStringParts.join("&"); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { diff --git a/samples/localities-api-details-postalcodes/index.njk b/samples/localities-api-details-postalcodes/index.njk index 92d43045..b478bb69 100644 --- a/samples/localities-api-details-postalcodes/index.njk +++ b/samples/localities-api-details-postalcodes/index.njk @@ -2,7 +2,7 @@ {% block html %}
-
+
{% svgIcon 'search.svg' %} Promise; +let debouncedAutocomplete: typeof autocompleteAddress; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; -let markerAddress: woosmap.map.Marker; +let markerAddress: woosmap.map.marker.AdvancedMarkerElement; function init(): void { if (inputElement && suggestionsList) { @@ -34,15 +32,14 @@ function init(): void { debouncedAutocomplete = debouncePromise(autocompleteAddress, 0); } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - center: { - lat: 48.8534, - lng: 2.3488, - }, +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ disableDefaultUI: true, gestureHandling: "greedy", - zoom: 5, styles: [ { featureType: "poi", @@ -50,6 +47,13 @@ function initMap(): void { }, ], }); + map.moveCamera({ + center: { + lat: 48.8534, + lng: 2.3488, + }, + zoom: 5, + }); } function handleAutocomplete(): void { @@ -172,15 +176,16 @@ function createAddressMarker( markerAddress.setMap(null); } if (addressDetail && addressDetail.geometry) { - markerAddress = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + markerAddress = new woosmap.map.marker.AdvancedMarkerElement({ position: addressDetail.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 59, - width: 37, - }, - }, + content: pin.element, }); markerAddress.setMap(map); panMap(addressDetail); @@ -211,8 +216,7 @@ function panMap(addressDetail: woosmap.map.localities.LocalitiesDetailsResult) { if (addressDetail.types[0] === "address") { zoom = 18; } - map.setZoom(zoom); - map.panTo(geometry.location); + map.moveCamera({ zoom, center: geometry.location }); } } @@ -260,17 +264,17 @@ function getLocalitiesDetails( ).then((response) => response.json()); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -309,12 +313,7 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_api_details_postalcodes] export {}; diff --git a/samples/localities-api-details-postalcodes/localities-api-details-postalcodes.json b/samples/localities-api-details-postalcodes/localities-api-details-postalcodes.json index 6ea08756..f656821f 100644 --- a/samples/localities-api-details-postalcodes/localities-api-details-postalcodes.json +++ b/samples/localities-api-details-postalcodes/localities-api-details-postalcodes.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-api-details/index.njk b/samples/localities-api-details/index.njk index a8e5c97a..0e58dba7 100644 --- a/samples/localities-api-details/index.njk +++ b/samples/localities-api-details/index.njk @@ -10,7 +10,7 @@ {% block html %}
-
+
diff --git a/samples/localities-api-details/index.ts b/samples/localities-api-details/index.ts index d099d552..49913b2c 100644 --- a/samples/localities-api-details/index.ts +++ b/samples/localities-api-details/index.ts @@ -2,26 +2,23 @@ const componentsRestriction: woosmap.map.localities.LocalitiesComponentRestrictions = { country: [] }; const woosmap_key = "YOUR_API_KEY"; -let debouncedAutocomplete: ( - ...args: any[] -) => Promise; +let debouncedAutocomplete: typeof autocompleteAddress; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; let map: woosmap.map.Map; -let markerAddress: woosmap.map.Marker; +let markerAddress: woosmap.map.marker.AdvancedMarkerElement; let detailsHTML: HTMLElement; let addressDetailsContainer: HTMLElement; -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - center: { - lat: 48.8534, - lng: 2.3488, - }, +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ disableDefaultUI: true, gestureHandling: "greedy", - zoom: 5, styles: [ { featureType: "poi", @@ -29,6 +26,13 @@ function initMap(): void { }, ], }); + map.moveCamera({ + center: { + lat: 48.8534, + lng: 2.3488, + }, + zoom: 5, + }); init(); manageCountrySelector(); } @@ -40,15 +44,16 @@ function createAddressMarker( markerAddress.setMap(null); } if (addressDetail && addressDetail.geometry) { - markerAddress = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + markerAddress = new woosmap.map.marker.AdvancedMarkerElement({ position: addressDetail.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 59, - width: 37, - }, - }, + content: pin.element, }); markerAddress.setMap(map); panMap(addressDetail); @@ -149,7 +154,7 @@ function handleAutocomplete(): void { .map((country) => `country:${country}`) .join("|"); if (input !== "") { - debouncedAutocomplete(input, componentsArgs, woosmap_key) + debouncedAutocomplete(input, componentsArgs) .then(({ localities }) => displaySuggestions(localities)) .catch((error) => console.error("Error autocomplete localities:", error), @@ -189,7 +194,7 @@ function formatPredictionList(locality): string { const prediction = locality; const predictionClass = "no-viewpoint"; const matched_substrings = prediction.matched_substrings; - let formatted_name = ""; + let formatted_name: string; if ( prediction.matched_substrings && prediction.matched_substrings.description @@ -260,17 +265,17 @@ function buildQueryString(params: object) { return queryStringParts.join("&"); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -425,8 +430,7 @@ function panMap(addressDetail: woosmap.map.localities.LocalitiesDetailsResult) { if (addressDetail.types[0] === "address") { zoom = 18; } - map.setZoom(zoom); - map.panTo(geometry.location); + map.moveCamera({ zoom, center: geometry.location }); } } @@ -442,12 +446,7 @@ function getLocalitiesDetails( ).then((response) => response.json()); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_api_details] diff --git a/samples/localities-api-details/localities-api-details.json b/samples/localities-api-details/localities-api-details.json index a68ed41a..de1d80b8 100644 --- a/samples/localities-api-details/localities-api-details.json +++ b/samples/localities-api-details/localities-api-details.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-api-shape/index.njk b/samples/localities-api-shape/index.njk index 8b2f31e0..c1be78f8 100644 --- a/samples/localities-api-shape/index.njk +++ b/samples/localities-api-shape/index.njk @@ -12,7 +12,7 @@ {% block html %}
-
+
diff --git a/samples/localities-api-shape/index.ts b/samples/localities-api-shape/index.ts index e4833126..038438a1 100644 --- a/samples/localities-api-shape/index.ts +++ b/samples/localities-api-shape/index.ts @@ -2,27 +2,24 @@ const componentsRestriction: woosmap.map.localities.LocalitiesComponentRestrictions = { country: [] }; const woosmap_key = "YOUR_API_KEY"; -let debouncedAutocomplete: ( - ...args: any[] -) => Promise; +let debouncedAutocomplete: typeof autocompleteAddress; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; let map: woosmap.map.Map; -let markerAddress: woosmap.map.Marker; +let markerAddress: woosmap.map.marker.AdvancedMarkerElement; let detailsHTML: HTMLElement; let addressDetailsContainer: HTMLElement; let hasShape = false; -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - center: { - lat: 48.8534, - lng: 2.3488, - }, +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ disableDefaultUI: true, gestureHandling: "greedy", - zoom: 5, styles: [ { featureType: "poi", @@ -30,15 +27,21 @@ function initMap(): void { }, ], }); + map.moveCamera({ + center: { + lat: 48.8534, + lng: 2.3488, + }, + zoom: 5, + }); init(); manageCountrySelector(); } function createShape(result: woosmap.map.localities.LocalitiesDetailsResult) { - // @ts-ignore TypeDef to be updated if (result?.geometry?.shape) { hasShape = true; - // @ts-ignore TypeDef to be updated + // @ts-expect-error shape is typed as a Feature, but the API returns a bare geometry map.data.addGeoJson({ type: "Feature", geometry: result.geometry.shape }); if (result.geometry.viewport) { const bounds = { @@ -58,15 +61,16 @@ function createAddressMarker(addressDetail) { } if (addressDetail?.geometry) { const position = addressDetail.geometry.location; - markerAddress = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + markerAddress = new woosmap.map.marker.AdvancedMarkerElement({ position: position, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 59, - width: 37, - }, - }, + content: pin.element, }); markerAddress.setMap(map); @@ -173,7 +177,7 @@ function handleAutocomplete(): void { .map((country) => `country:${country}`) .join("|"); if (input !== "") { - debouncedAutocomplete(input, componentsArgs, woosmap_key) + debouncedAutocomplete(input, componentsArgs) .then(({ localities }) => displaySuggestions(localities)) .catch((error) => console.error("Error autocomplete localities:", error), @@ -213,7 +217,7 @@ function formatPredictionList(locality): string { const prediction = locality; const predictionClass = "no-viewpoint"; const matched_substrings = prediction.matched_substrings; - let formatted_name = ""; + let formatted_name: string; if ( prediction.matched_substrings && prediction.matched_substrings.description @@ -284,17 +288,17 @@ function buildQueryString(params: object) { return queryStringParts.join("&"); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -448,8 +452,7 @@ function panMap(addressDetail: woosmap.map.localities.LocalitiesDetailsResult) { if (addressDetail.types[0] === "address") { zoom = 18; } - map.setZoom(zoom); - map.panTo(geometry.location); + map.moveCamera({ zoom, center: geometry.location }); } } @@ -466,12 +469,7 @@ function getLocalitiesDetails( ).then((response) => response.json()); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_api_shape] diff --git a/samples/localities-api-shape/localities-api-shape.json b/samples/localities-api-shape/localities-api-shape.json index 7aba6240..80478a4d 100644 --- a/samples/localities-api-shape/localities-api-shape.json +++ b/samples/localities-api-shape/localities-api-shape.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-autocomplete/index.njk b/samples/localities-autocomplete/index.njk index b71ca6e9..ba60a75d 100644 --- a/samples/localities-autocomplete/index.njk +++ b/samples/localities-autocomplete/index.njk @@ -16,7 +16,7 @@
    -
    +
    {% endblock %} diff --git a/samples/localities-autocomplete/index.ts b/samples/localities-autocomplete/index.ts index 311bb479..ffeb5a37 100644 --- a/samples/localities-autocomplete/index.ts +++ b/samples/localities-autocomplete/index.ts @@ -1,21 +1,22 @@ // [START woosmap_localities_autocomplete] let map: woosmap.map.Map; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; let infoWindow: woosmap.map.InfoWindow; let localitiesService: woosmap.map.LocalitiesService; let request: woosmap.map.localities.LocalitiesAutocompleteRequest; -let debouncedLocalitiesAutocomplete: (...args: any[]) => Promise; +let debouncedLocalitiesAutocomplete: woosmap.map.LocalitiesService["autocomplete"]; -function initMap(): void { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.50940214, lng: -0.133012 }, zoom: 4, - }, - ); + }); infoWindow = new woosmap.map.InfoWindow({}); - localitiesService = new window.woosmap.map.LocalitiesService(); + localitiesService = new woosmap.map.LocalitiesService(); request = { input: "", @@ -90,19 +91,20 @@ function displayLocality( infoWindow.close(); } if (locality?.geometry) { - marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + marker = new woosmap.map.marker.AdvancedMarkerElement({ position: locality.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); marker.setMap(map); infoWindow.setContent(`${locality.formatted_address}`); - infoWindow.open(map, marker); + infoWindow.open({map, anchor: marker}); map.flyTo({ center: locality.geometry.location, zoom: 14 }); } } @@ -143,19 +145,19 @@ document.addEventListener("click", (event) => { }); // [START woosmap_localities_autocomplete_debounce_promise] -let PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +let PRESERVE_COMMENT_ABOVE; // eslint-disable-line no-unassigned-vars -- force tsc to maintain the comment above -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -182,14 +184,9 @@ function debouncePromise( } // [END woosmap_localities_autocomplete_debounce_promise] */ -PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +PRESERVE_COMMENT_ABOVE; // eslint-disable-line @typescript-eslint/no-unused-expressions -- force tsc to maintain the comment above -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_autocomplete] export {}; diff --git a/samples/localities-autocomplete/localities-autocomplete.json b/samples/localities-autocomplete/localities-autocomplete.json index 0085c6e6..45ca3225 100644 --- a/samples/localities-autocomplete/localities-autocomplete.json +++ b/samples/localities-autocomplete/localities-autocomplete.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-geocode/index.njk b/samples/localities-geocode/index.njk index 917d06e4..c93154e3 100644 --- a/samples/localities-geocode/index.njk +++ b/samples/localities-geocode/index.njk @@ -39,7 +39,7 @@ -
    +
    {% endblock %} diff --git a/samples/localities-geocode/index.ts b/samples/localities-geocode/index.ts index 1a1c4f0a..476cb6ca 100644 --- a/samples/localities-geocode/index.ts +++ b/samples/localities-geocode/index.ts @@ -1,19 +1,20 @@ // [START woosmap_localities_geocode] // Initialize and add the map let map: woosmap.map.Map; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; let infoWindow: woosmap.map.InfoWindow; let localitiesService: woosmap.map.LocalitiesService; const request: woosmap.map.localities.LocalitiesGeocodeRequest = {}; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.50940214, lng: -0.133012 }, zoom: 12, - }, - ); + }); infoWindow = new woosmap.map.InfoWindow({}); localitiesService = new woosmap.map.LocalitiesService(); map.addListener("click", (e) => { @@ -79,19 +80,20 @@ function displayLocality( } if (locality?.geometry) { - marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + marker = new woosmap.map.marker.AdvancedMarkerElement({ position: locality.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); marker.setMap(map); infoWindow.setContent(`${locality.formatted_address}`); - infoWindow.open(map, marker); + infoWindow.open({map, anchor: marker}); map.setCenter(locality.geometry.location); renderResponse(locality); } @@ -211,12 +213,7 @@ function clearResponse() { if (rawEl) rawEl.textContent = ""; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_geocode] export {}; diff --git a/samples/localities-geocode/localities-geocode.json b/samples/localities-geocode/localities-geocode.json index bb180d0c..314e3e12 100644 --- a/samples/localities-geocode/localities-geocode.json +++ b/samples/localities-geocode/localities-geocode.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/localities-js-api/index.ts b/samples/localities-js-api/index.ts index db0a89c3..9d5506a7 100644 --- a/samples/localities-js-api/index.ts +++ b/samples/localities-js-api/index.ts @@ -1,7 +1,29 @@ // [START woosmap_localities_js_api] const customDescription = 'postal_code:"{name} ({postal_town}) - {administrative_area_level_0}"'; -let localitiesAutocompleteService; +// The Localities JS API ships no typings: describe the parts this sample uses. +interface LocalitiesAutocompleteService { + autocomplete( + request: { input: string; custom_description: string }, + onSuccess: ( + response: woosmap.map.localities.LocalitiesAutocompleteResponse, + ) => void, + onError: (errorCode: number, errorText: string) => void, + debounceTime: number, + ): void; + getDetails( + publicId: string, + onSuccess: (result: woosmap.map.localities.LocalitiesPredictions) => void, + ): void; +} + +interface LocalitiesApiGlobal { + localities: { + AutocompleteService: new (key: string) => LocalitiesAutocompleteService; + }; +} + +let localitiesAutocompleteService: LocalitiesAutocompleteService; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; @@ -27,8 +49,10 @@ function init(): void { inputElement.focus(); }); - localitiesAutocompleteService = - new window.woosmap.localities.AutocompleteService("YOUR_API_KEY"); + const { localities } = woosmap as unknown as LocalitiesApiGlobal; + localitiesAutocompleteService = new localities.AutocompleteService( + "YOUR_API_KEY", + ); } function handleAutocomplete(): void { @@ -84,7 +108,7 @@ function formatPredictionList(locality): string { const prediction = locality; const predictionClass = "no-viewpoint"; const matched_substrings = prediction.matched_substrings; - let formatted_name = ""; + let formatted_name: string; if ( prediction.matched_substrings && prediction.matched_substrings.description @@ -145,16 +169,6 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - // currently, the localities JS API typings are not exported, so we use `any` here - woosmap: { - localities: { - AutocompleteService: new (key: string) => any; - }; - }; - } -} // [END woosmap_localities_js_api] export {}; diff --git a/samples/localities-js-widget-custom-desc/index.ts b/samples/localities-js-widget-custom-desc/index.ts index c690c087..a5381a4e 100644 --- a/samples/localities-js-widget-custom-desc/index.ts +++ b/samples/localities-js-widget-custom-desc/index.ts @@ -1,11 +1,23 @@ // [START woosmap_localities_js_widget_custom_desc] +// The Localities JS Widget ships no typings: describe the parts this sample uses. +interface LocalitiesWidget { + addListener(eventName: string, handler: () => void): void; + getSelectedSuggestionDetails(): unknown; +} + +interface LocalitiesWidgetGlobal { + localities: { + Autocomplete: new (inputId: string, options: object) => LocalitiesWidget; + }; +} + function init(): void { const responseElement = document.getElementById( "response-container", ) as HTMLElement; - // @ts-ignore - const localitiesWidget = new window.woosmap.localities.Autocomplete( + const { localities } = woosmap as unknown as LocalitiesWidgetGlobal; + const localitiesWidget = new localities.Autocomplete( "autocomplete-input", { minLength: 3, @@ -29,17 +41,6 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - // currently, the localities JS Widget typings are not exported, so we use `any` here - //@ts-ignore - woosmap: { - localities: { - Autocomplete: new (inputId: string, customConfig: any) => any; - }; - }; - } -} // [END woosmap_localities_js_widget_custom_desc] export {}; diff --git a/samples/localities-js-widget/index.ts b/samples/localities-js-widget/index.ts index 95f4f48c..31ae6b7d 100644 --- a/samples/localities-js-widget/index.ts +++ b/samples/localities-js-widget/index.ts @@ -1,11 +1,23 @@ // [START woosmap_localities_js_widget] +// The Localities JS Widget ships no typings: describe the parts this sample uses. +interface LocalitiesWidget { + addListener(eventName: string, handler: () => void): void; + getSelectedSuggestionDetails(): unknown; +} + +interface LocalitiesWidgetGlobal { + localities: { + Autocomplete: new (inputId: string, options: object) => LocalitiesWidget; + }; +} + function init(): void { const responseElement = document.getElementById( "response-container", ) as HTMLElement; - //@ts-ignore - const localitiesWidget = new window.woosmap.localities.Autocomplete( + const { localities } = woosmap as unknown as LocalitiesWidgetGlobal; + const localitiesWidget = new localities.Autocomplete( "autocomplete-input", {}, ); @@ -23,17 +35,6 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - // currently, the localities JS Widget typings are not exported, so we use `any` here - //@ts-ignore - woosmap: { - localities: { - Autocomplete: new (inputId: string, customConfig: any) => any; - }; - }; - } -} // [END woosmap_localities_js_widget] export {}; diff --git a/samples/localities-nearby-poi/index.njk b/samples/localities-nearby-poi/index.njk index 02476f91..7a36c1d0 100644 --- a/samples/localities-nearby-poi/index.njk +++ b/samples/localities-nearby-poi/index.njk @@ -34,7 +34,7 @@
      -
      + diff --git a/samples/localities-nearby-poi/index.ts b/samples/localities-nearby-poi/index.ts index 09c65e9b..36da5064 100644 --- a/samples/localities-nearby-poi/index.ts +++ b/samples/localities-nearby-poi/index.ts @@ -66,13 +66,17 @@ const types: Set = new Set(); let map: woosmap.map.Map; let results: HTMLOListElement; let nearbyCircle: woosmap.map.Circle; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; let localitiesService: woosmap.map.LocalitiesService; let autocompleteRequest: woosmap.map.localities.LocalitiesAutocompleteRequest; let nearbyRequest: woosmap.map.localities.LocalitiesNearbyRequest; +interface TypeTree { + [type: string]: TypeTree; +} + const buildTree = (availableTypes: string[]) => { - const tree = {}; + const tree: TypeTree = {}; availableTypes.forEach((type) => { const parts = type.split("."); let node = tree; @@ -84,7 +88,7 @@ const buildTree = (availableTypes: string[]) => { return tree; }; -const createList = (node: any, prefix = "") => { +const createList = (node: TypeTree, prefix = "") => { const ul = document.createElement("ul"); for (const key in node) { const fullKey = prefix ? `${prefix}.${key}` : key; @@ -113,12 +117,12 @@ const createList = (node: any, prefix = "") => { return ul.childElementCount ? ul : null; }; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - center: { lat: 40.71399, lng: -74.00499 }, - zoom: 14, +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { featureType: "point_of_interest", @@ -130,8 +134,11 @@ function initMap() { ], }, ], - }, - ); + }); + map.moveCamera({ + center: { lat: 40.71399, lng: -74.00499 }, + zoom: 14, + }); localitiesService = new woosmap.map.LocalitiesService(); map.addListener("click", (e) => { @@ -149,15 +156,16 @@ function initMap() { page: 1, limit: 10, }; - marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + marker = new woosmap.map.marker.AdvancedMarkerElement({ position: { lat: 0, lng: 0 }, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); initUI(); @@ -279,7 +287,6 @@ function performNearbyRequest( return; } - //@ts-ignore localitiesService.nearby(nearbyRequest).then((responseJson) => { drawNearbyZone(requestCenter, nearbyRequest.radius); updateResults(responseJson, requestCenter); @@ -461,9 +468,12 @@ document.addEventListener("click", (event) => { } }); -function debounce(func: (...args: any[]) => void, wait: number) { +function debounce( + func: (...args: Args) => void, + wait: number, +) { let timeout: ReturnType; - return function executedFunction(...args: any[]) { + return function executedFunction(...args: Args) { const later = () => { clearTimeout(timeout); func(...args); @@ -521,12 +531,7 @@ document.addEventListener('DOMContentLoaded', () => { }); -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_localities_nearby_poi] export {}; diff --git a/samples/localities-nearby-poi/localities-nearby-poi.json b/samples/localities-nearby-poi/localities-nearby-poi.json index 4ffe9e67..1a3afb5f 100644 --- a/samples/localities-nearby-poi/localities-nearby-poi.json +++ b/samples/localities-nearby-poi/localities-nearby-poi.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/map-clustering-geojson/index.njk b/samples/map-clustering-geojson/index.njk index 8e3f95a0..a9b6bb9a 100644 --- a/samples/map-clustering-geojson/index.njk +++ b/samples/map-clustering-geojson/index.njk @@ -2,6 +2,6 @@ {% block html %} -
      + {% endblock %} diff --git a/samples/map-clustering-geojson/index.ts b/samples/map-clustering-geojson/index.ts index fb6ba595..9779feab 100644 --- a/samples/map-clustering-geojson/index.ts +++ b/samples/map-clustering-geojson/index.ts @@ -5,26 +5,28 @@ import Supercluster from "supercluster"; let map: woosmap.map.Map; let infoWindow: woosmap.map.InfoWindow; let index: Supercluster; -let markers: woosmap.map.Marker[] = []; +let markers: woosmap.map.marker.AdvancedMarkerElement[] = []; const GEOJSON_URL = "https://demo.woosmap.com/misc/data/uk-all-pubs.geojson"; const ICON_URL = "https://images.woosmap.com/dot-green.svg"; // -const SUPERCLUSTER_OPTIONS: Supercluster.Options = { +type ClusterOrPoint = ReturnType[number]; + +const SUPERCLUSTER_OPTIONS: Supercluster.Options< + Supercluster.AnyProps, + Supercluster.AnyProps +> = { radius: 40, extent: 256, maxZoom: 14, minPoints: 5, }; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + infoWindow = new woosmap.map.InfoWindow({}); - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - center: { - lat: 55.5, - lng: -4, - }, - zoom: 5.7, + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { elementType: "geometry", @@ -93,8 +95,14 @@ function initMap(): void { stylers: [{ color: "#9e9e9e" }], }, ], - }, - ); + }); + map.moveCamera({ + center: { + lat: 55.5, + lng: -4, + }, + zoom: 5.7, + }); fetchGeoJsonData(GEOJSON_URL).then((data) => { const geojsonFeatures = data["features"]; @@ -142,9 +150,9 @@ function clearMarkers(): void { } function createClusterIcon( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { +): woosmap.map.marker.AdvancedMarkerElement { if (!feature.properties.cluster) { return createMarker(feature, latlng); } @@ -152,9 +160,9 @@ function createClusterIcon( } function createCluster( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { +): woosmap.map.marker.AdvancedMarkerElement { const count = feature.properties.point_count; const color = count < 80 ? "#0B9D58" : count < 500 ? "#F5B300" : "#DA0A40"; @@ -167,58 +175,73 @@ function createCluster( `); - const marker = new window.woosmap.map.Marker({ - label: { - text: feature.properties["point_count_abbreviated"], - color: "white", - }, + const container = document.createElement("div"); + container.style.position = "relative"; + container.style.width = `${size}px`; + container.style.height = `${size}px`; + + const icon = document.createElement("img"); + icon.src = `data:image/svg+xml;base64,${svg}`; + icon.style.width = `${size}px`; + icon.style.height = `${size}px`; + container.appendChild(icon); + + const labelSpan = document.createElement("span"); + labelSpan.textContent = feature.properties["point_count_abbreviated"]; + labelSpan.style.position = "absolute"; + labelSpan.style.left = "50%"; + labelSpan.style.top = "50%"; + labelSpan.style.transform = "translate(-50%, -50%)"; + labelSpan.style.color = "white"; + labelSpan.style.fontSize = "12px"; + labelSpan.style.fontWeight = "bold"; + container.appendChild(labelSpan); + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, - icon: { - url: `data:image/svg+xml;base64,${svg}`, - scaledSize: new window.woosmap.map.Size(size, size), - }, + content: container, + gmpClickable: true, map: map, }); - marker.addListener("click", (e) => { + marker.addListener("click", () => { infoWindow.close(); const expansionZoom = index.getClusterExpansionZoom( feature.properties["cluster_id"], ); - map.setCenter(marker.getPosition()); - map.setZoom(expansionZoom); + map.moveCamera({ center: marker.position!, zoom: expansionZoom }); }); return marker; } function createMarker( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { - const marker = new window.woosmap.map.Marker({ - icon: { - url: ICON_URL, - scaledSize: { - height: 20, - width: 20, - }, - }, +): woosmap.map.marker.AdvancedMarkerElement { + const markerContent = document.createElement("img"); + markerContent.src = ICON_URL; + markerContent.style.width = "20px"; + markerContent.style.height = "20px"; + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, + content: markerContent, + gmpClickable: true, map: map, }); marker.addListener("click", () => { infoWindow.setContent(`

      ${feature.properties.name}

      `); - infoWindow.open(map, marker); + infoWindow.open({map, anchor: marker}); }); return marker; } -function debounce ReturnType>( - callback: T, +function debounce( + callback: (...args: Args) => void, timeout: number, -): (...args: Parameters) => void { +): (...args: Args) => void { let timer: ReturnType; - return (...args: Parameters) => { + return (...args: Args) => { clearTimeout(timer); timer = setTimeout(() => { callback(...args); @@ -226,12 +249,7 @@ function debounce ReturnType>( }; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_clustering_geojson] export {}; diff --git a/samples/map-clustering-geojson/map-clustering-geojson.json b/samples/map-clustering-geojson/map-clustering-geojson.json index fea98971..71631027 100644 --- a/samples/map-clustering-geojson/map-clustering-geojson.json +++ b/samples/map-clustering-geojson/map-clustering-geojson.json @@ -15,5 +15,7 @@ "supercluster", "@types/supercluster", "@types/geojson" - ] + ], + "libraries": "marker", + "loaderShim": true } diff --git a/samples/map-clustering-stores/index.njk b/samples/map-clustering-stores/index.njk index 8e3f95a0..a9b6bb9a 100644 --- a/samples/map-clustering-stores/index.njk +++ b/samples/map-clustering-stores/index.njk @@ -2,6 +2,6 @@ {% block html %} -
      + {% endblock %} diff --git a/samples/map-clustering-stores/index.ts b/samples/map-clustering-stores/index.ts index 520ddf7d..5a6643f3 100644 --- a/samples/map-clustering-stores/index.ts +++ b/samples/map-clustering-stores/index.ts @@ -5,22 +5,27 @@ import Supercluster from "supercluster"; let map: woosmap.map.Map; let infoWindow: woosmap.map.InfoWindow; let index: Supercluster; -let markers: woosmap.map.Marker[] = []; +let markers: woosmap.map.marker.AdvancedMarkerElement[] = []; const ICON_URL = "https://images.woosmap.com/dot-green.svg"; // -const SUPERCLUSTER_OPTIONS: Supercluster.Options = { +type ClusterOrPoint = ReturnType[number]; + +const SUPERCLUSTER_OPTIONS: Supercluster.Options< + Supercluster.AnyProps, + Supercluster.AnyProps +> = { radius: 30, extent: 256, maxZoom: 15, minPoints: 2, }; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + infoWindow = new woosmap.map.InfoWindow({}); - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - center: { lat: 53.3485, lng: -6.257 }, - zoom: 12, + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { elementType: "geometry", @@ -89,8 +94,11 @@ function initMap(): void { stylers: [{ color: "#9e9e9e" }], }, ], - }, - ); + }); + map.moveCamera({ + center: { lat: 53.3485, lng: -6.257 }, + zoom: 12, + }); getAllStores().then((stores) => { index = new Supercluster(SUPERCLUSTER_OPTIONS).load(stores); @@ -163,9 +171,9 @@ function clearMarkers(): void { } function createClusterIcon( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { +): woosmap.map.marker.AdvancedMarkerElement { if (!feature.properties.cluster) { return createMarker(feature, latlng); } @@ -173,9 +181,9 @@ function createClusterIcon( } function createCluster( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { +): woosmap.map.marker.AdvancedMarkerElement { const count = feature.properties.point_count; const color = count < 5 ? "#0B9D58" : count < 12 ? "#F5B300" : "#DA0A40"; @@ -188,58 +196,73 @@ function createCluster( `); - const marker = new window.woosmap.map.Marker({ - label: { - text: feature.properties["point_count_abbreviated"], - color: "white", - }, + const container = document.createElement("div"); + container.style.position = "relative"; + container.style.width = `${size}px`; + container.style.height = `${size}px`; + + const icon = document.createElement("img"); + icon.src = `data:image/svg+xml;base64,${svg}`; + icon.style.width = `${size}px`; + icon.style.height = `${size}px`; + container.appendChild(icon); + + const labelSpan = document.createElement("span"); + labelSpan.textContent = feature.properties["point_count_abbreviated"]; + labelSpan.style.position = "absolute"; + labelSpan.style.left = "50%"; + labelSpan.style.top = "50%"; + labelSpan.style.transform = "translate(-50%, -50%)"; + labelSpan.style.color = "white"; + labelSpan.style.fontSize = "12px"; + labelSpan.style.fontWeight = "bold"; + container.appendChild(labelSpan); + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, - icon: { - url: `data:image/svg+xml;base64,${svg}`, - scaledSize: new window.woosmap.map.Size(size, size), - }, + content: container, + gmpClickable: true, map: map, }); - marker.addListener("click", (e) => { + marker.addListener("click", () => { infoWindow.close(); const expansionZoom = index.getClusterExpansionZoom( feature.properties["cluster_id"], ); - map.setCenter(marker.getPosition()); - map.setZoom(expansionZoom); + map.moveCamera({ center: marker.position!, zoom: expansionZoom }); }); return marker; } function createMarker( - feature: any, + feature: ClusterOrPoint, latlng: woosmap.map.LatLngLiteral, -): woosmap.map.Marker { - const marker = new window.woosmap.map.Marker({ - icon: { - url: ICON_URL, - scaledSize: { - height: 20, - width: 20, - }, - }, +): woosmap.map.marker.AdvancedMarkerElement { + const markerContent = document.createElement("img"); + markerContent.src = ICON_URL; + markerContent.style.width = "20px"; + markerContent.style.height = "20px"; + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, + content: markerContent, + gmpClickable: true, map: map, }); marker.addListener("click", () => { infoWindow.setContent(`

      ${feature.properties.name}

      `); - infoWindow.open(map, marker); + infoWindow.open({map, anchor: marker}); }); return marker; } -function debounce ReturnType>( - callback: T, +function debounce( + callback: (...args: Args) => void, timeout: number, -): (...args: Parameters) => void { +): (...args: Args) => void { let timer: ReturnType; - return (...args: Parameters) => { + return (...args: Args) => { clearTimeout(timer); timer = setTimeout(() => { callback(...args); @@ -247,12 +270,7 @@ function debounce ReturnType>( }; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_clustering_stores] export {}; diff --git a/samples/map-clustering-stores/map-clustering-stores.json b/samples/map-clustering-stores/map-clustering-stores.json index 96ad8684..44b2c803 100644 --- a/samples/map-clustering-stores/map-clustering-stores.json +++ b/samples/map-clustering-stores/map-clustering-stores.json @@ -16,5 +16,7 @@ "supercluster", "@types/supercluster", "@types/geojson" - ] + ], + "libraries": "marker", + "loaderShim": true } diff --git a/samples/map-events/index.njk b/samples/map-events/index.njk index 0fc3a07e..51b536e4 100644 --- a/samples/map-events/index.njk +++ b/samples/map-events/index.njk @@ -1,7 +1,7 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
      -
      +
      {% endblock %} diff --git a/samples/map-events/index.ts b/samples/map-events/index.ts index faadf843..27ca4435 100644 --- a/samples/map-events/index.ts +++ b/samples/map-events/index.ts @@ -15,17 +15,17 @@ const events: string[] = [ "zoom_changed", ]; -function initMap(): void { - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.52, lng: -0.13, }, zoom: 10, - }, - ); + }); populateEventsTable(); events.forEach((event: string) => { @@ -54,11 +54,6 @@ function setupListener(name: string): void { } } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_events] export {}; diff --git a/samples/map-events/map-events.json b/samples/map-events/map-events.json index c6fc1b0e..96f7a050 100644 --- a/samples/map-events/map-events.json +++ b/samples/map-events/map-events.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/map-external-layer/index.njk b/samples/map-external-layer/index.njk index 6f6577d4..e3444824 100644 --- a/samples/map-external-layer/index.njk +++ b/samples/map-external-layer/index.njk @@ -39,7 +39,7 @@ -
      + {% endblock %} diff --git a/samples/map-external-layer/index.ts b/samples/map-external-layer/index.ts index 63d387f3..d437cc50 100644 --- a/samples/map-external-layer/index.ts +++ b/samples/map-external-layer/index.ts @@ -12,16 +12,18 @@ const centerLatLng: woosmap.map.LatLngLiteral = { lng: 6.073999, }; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 15.64, - center: centerLatLng, +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ mapTypeControl: true, styles: STYLE_PRESETS.lightgrey, - }, - ); + }); + map.moveCamera({ + zoom: 15.64, + center: centerLatLng, + }); styleSelect = document.getElementById( "woosmap-style-select", @@ -57,7 +59,7 @@ function readOpacity(): number { function onStyleChange() { applyStyle(styleSelect.value); - // Recreating the map wipes overlays — reapply the current layer. + // Restyling reloads the base style, which drops overlays: reapply the current layer. applyLayer(layerSelect.value, readOpacity()); } @@ -74,16 +76,7 @@ function onOpacityChange() { } function applyStyle(name: string) { - const styles = STYLE_PRESETS[name] ?? []; - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: map.getZoom(), - center: map.getCenter(), - mapTypeControl: true, - styles, - }, - ); + map.setOptions({ styles: STYLE_PRESETS[name] ?? [] }); } function applyLayer(provider: string, opacity: number) { @@ -421,12 +414,7 @@ const LAYER_VIEWS: Record void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_external_layer] export {}; diff --git a/samples/map-external-layer/map-external-layer.json b/samples/map-external-layer/map-external-layer.json index 45c1b61d..320f307a 100644 --- a/samples/map-external-layer/map-external-layer.json +++ b/samples/map-external-layer/map-external-layer.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" -} \ No newline at end of file + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true +} diff --git a/samples/map-style-lightgrey/index.njk b/samples/map-style-lightgrey/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/map-style-lightgrey/index.njk +++ b/samples/map-style-lightgrey/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/map-style-lightgrey/index.ts b/samples/map-style-lightgrey/index.ts index 87d75992..72f20ef1 100644 --- a/samples/map-style-lightgrey/index.ts +++ b/samples/map-style-lightgrey/index.ts @@ -1,12 +1,11 @@ // [START woosmap_map_style_lightgrey] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const position: woosmap.map.LatLngLiteral = { lat: 41.347, lng: 2.14566 }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 12, - center: position, + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { elementType: "geometry", @@ -75,16 +74,14 @@ function initMap(): void { stylers: [{ color: "#9e9e9e" }], }, ], - }, - ); + }); + map.moveCamera({ + zoom: 12, + center: position, + }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_style_lightgrey] export {}; diff --git a/samples/map-style-lightgrey/map-style-lightgrey.json b/samples/map-style-lightgrey/map-style-lightgrey.json index 31d74820..941c3e97 100644 --- a/samples/map-style-lightgrey/map-style-lightgrey.json +++ b/samples/map-style-lightgrey/map-style-lightgrey.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/map-style-night/index.njk b/samples/map-style-night/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/map-style-night/index.njk +++ b/samples/map-style-night/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/map-style-night/index.ts b/samples/map-style-night/index.ts index 1578c333..7edd740f 100644 --- a/samples/map-style-night/index.ts +++ b/samples/map-style-night/index.ts @@ -1,15 +1,14 @@ // [START woosmap_map_style_night] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const position: woosmap.map.LatLngLiteral = { lat: 48.85467879441348, lng: 2.3482787190654792, }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 15, - center: position, + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { elementType: "geometry", @@ -99,16 +98,14 @@ function initMap(): void { stylers: [{ color: "#17263c" }], }, ], - }, - ); + }); + map.moveCamera({ + zoom: 15, + center: position, + }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_style_night] export {}; diff --git a/samples/map-style-night/map-style-night.json b/samples/map-style-night/map-style-night.json index 70bfbb0b..18743a88 100644 --- a/samples/map-style-night/map-style-night.json +++ b/samples/map-style-night/map-style-night.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/map-style-pois/index.njk b/samples/map-style-pois/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/map-style-pois/index.njk +++ b/samples/map-style-pois/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/map-style-pois/index.ts b/samples/map-style-pois/index.ts index 6119391e..8147007e 100644 --- a/samples/map-style-pois/index.ts +++ b/samples/map-style-pois/index.ts @@ -1,15 +1,14 @@ // [START woosmap_map_style_pois] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const position: woosmap.map.LatLngLiteral = { lat: 51.50393576678564, lng: -0.12263034354122525, }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 16, - center: position, + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { "featureType": "point_of_interest", @@ -21,16 +20,14 @@ function initMap(): void { ] } ], - }, - ); + }); + map.moveCamera({ + zoom: 16, + center: position, + }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_style_pois] export {}; diff --git a/samples/map-style-pois/map-style-pois.json b/samples/map-style-pois/map-style-pois.json index 928890aa..55f16a89 100644 --- a/samples/map-style-pois/map-style-pois.json +++ b/samples/map-style-pois/map-style-pois.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/map-style-retro/index.njk b/samples/map-style-retro/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/map-style-retro/index.njk +++ b/samples/map-style-retro/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/map-style-retro/index.ts b/samples/map-style-retro/index.ts index 618ac41f..fe33a948 100644 --- a/samples/map-style-retro/index.ts +++ b/samples/map-style-retro/index.ts @@ -1,12 +1,11 @@ // [START woosmap_map_style_retro] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const position: woosmap.map.LatLngLiteral = { lat: 51.499, lng: -0.015 }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 14, - center: position, + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ styles: [ { elementType: "geometry", @@ -131,16 +130,14 @@ function initMap(): void { stylers: [{ color: "#92998d" }], }, ], - }, - ); + }); + map.moveCamera({ + zoom: 14, + center: position, + }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_style_retro] export {}; diff --git a/samples/map-style-retro/map-style-retro.json b/samples/map-style-retro/map-style-retro.json index 8f821856..c5420b79 100644 --- a/samples/map-style-retro/map-style-retro.json +++ b/samples/map-style-retro/map-style-retro.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/map-type-hybrid/index.njk b/samples/map-type-hybrid/index.njk index f2ff4535..6150b04a 100644 --- a/samples/map-type-hybrid/index.njk +++ b/samples/map-type-hybrid/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/map-type-hybrid/index.ts b/samples/map-type-hybrid/index.ts index 24715217..62678c53 100644 --- a/samples/map-type-hybrid/index.ts +++ b/samples/map-type-hybrid/index.ts @@ -2,19 +2,24 @@ // Initialize and add the map with hybrid (satellite) map type let map: woosmap.map.Map; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const position: woosmap.map.LatLngLiteral = { lat: 48.8584, lng: 2.2945, }; // The map, initialized with hybrid satellite view - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - zoom: 16, - center: position, + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ mapTypeId: woosmap.map.MapTypeId.HYBRID, mapTypeControl: true, }); + map.moveCamera({ + zoom: 16, + center: position, + }); // Listen for map type changes via the built-in control map.addListener("mapTypeId_changed", () => { @@ -22,12 +27,7 @@ function initMap(): void { }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_map_type_hybrid] export {}; diff --git a/samples/map-type-hybrid/map-type-hybrid.json b/samples/map-type-hybrid/map-type-hybrid.json index 8e18c873..49567089 100644 --- a/samples/map-type-hybrid/map-type-hybrid.json +++ b/samples/map-type-hybrid/map-type-hybrid.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/marker-click-event/index.njk b/samples/marker-click-event/index.njk index 417b72a5..ffb3940e 100644 --- a/samples/marker-click-event/index.njk +++ b/samples/marker-click-event/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
      Click on a marker to display attributes here
      -
      + {% endblock %} diff --git a/samples/marker-click-event/index.ts b/samples/marker-click-event/index.ts index 511a268f..73247a42 100644 --- a/samples/marker-click-event/index.ts +++ b/samples/marker-click-event/index.ts @@ -1,6 +1,6 @@ // [START woosmap_marker_click_event] -const markers: woosmap.map.Marker[] = []; -let markerSelected: woosmap.map.Marker; +const markers: woosmap.map.marker.AdvancedMarkerElement[] = []; +let markerSelected: woosmap.map.marker.AdvancedMarkerElement; const data = { megaCities: [ { @@ -136,26 +136,26 @@ const data = { ], }; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + const center: woosmap.map.LatLngLiteral = { lat: 40.0, lng: 0.0 }; - const iconCity: woosmap.map.Icon = { - url: "https://images.woosmap.com/icons/pin-red.png", - scaledSize: { height: 38, width: 26 }, - }; + const { PinElement } = woosmap.map.marker; + const CITY_PIN_COLORS = { background: "#EA4335", borderColor: "#B31412" }; + const SELECTED_CITY_PIN_COLORS = { background: "#00BDA5", borderColor: "#004941" }; - const iconSelectedCity: woosmap.map.Icon = { - url: "https://images.woosmap.com/icons/pin-green.png", - scaledSize: { height: 38, width: 26 }, - }; + function createCityMarkerContent(): woosmap.map.marker.PinElement { + return new PinElement(CITY_PIN_COLORS); + } - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 0, - center: center, - }, - ); + const map = (document.getElementById("map") as woosmap.map.MapElement) + .innerMap; + map.moveCamera({ + zoom: 0, + center: center, + }); data.megaCities.forEach((cityData) => { const latlng = { @@ -163,9 +163,10 @@ function initMap(): void { lng: parseFloat(cityData.latlng.split(",")[1]), }; - const markerCity = new woosmap.map.Marker({ + const markerCity = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, - icon: iconCity, + content: createCityMarkerContent(), + gmpClickable: true, }); markerCity.setMap(map); @@ -177,26 +178,27 @@ function initMap(): void { }); const handleMarkerClick = ( - marker: woosmap.map.Marker, + marker: woosmap.map.marker.AdvancedMarkerElement, cityData: Record, ) => { if (markerSelected) { - markerSelected.setIcon(iconCity); + Object.assign( + markerSelected.content as woosmap.map.marker.PinElement, + CITY_PIN_COLORS, + ); } markerSelected = marker; - marker.setIcon(iconSelectedCity); + Object.assign( + marker.content as woosmap.map.marker.PinElement, + SELECTED_CITY_PIN_COLORS, + ); const infoElement = document.getElementById("info") as HTMLElement; infoElement.innerHTML = `${cityData.cityName}: ${cityData.citizens}`; }; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_marker_click_event] export {}; diff --git a/samples/marker-click-event/marker-click-event.json b/samples/marker-click-event/marker-click-event.json index 84d3db3b..f8ba820a 100644 --- a/samples/marker-click-event/marker-click-event.json +++ b/samples/marker-click-event/marker-click-event.json @@ -3,7 +3,7 @@ "description": "Listen to this event to get the marker associated attributes.", "category": "Markers", "callback": "initMap", - "libraries": [], + "libraries": "marker", "tag": "marker_click_event", "name": "marker-click-event", "pagination": { @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/marker-html-css/index.njk b/samples/marker-html-css/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/marker-html-css/index.njk +++ b/samples/marker-html-css/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/marker-html-css/index.ts b/samples/marker-html-css/index.ts index 05fccf92..eeeeb375 100644 --- a/samples/marker-html-css/index.ts +++ b/samples/marker-html-css/index.ts @@ -3,94 +3,29 @@ interface MarkerData { price: string; } -function initMap(): void { - class HTMLMapMarker extends woosmap.map.OverlayView { - private readonly latlng: woosmap.map.LatLng; - private readonly html: string; - public div: HTMLDivElement | null = null; - - constructor({ latlng, map, data }) { - super(); - this.latlng = latlng; - this.html = `
      +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + function createMarkerContent(data: MarkerData): HTMLDivElement { + const div = document.createElement("div"); + div.className = "popover"; + div.innerHTML = `
      ️ ${data.price}
      `; - this.setMap(map); - } - - private createDiv(): void { - this.div = document.createElement("div"); - this.div.style.position = "absolute"; - this.div.className = "popover"; - if (this.html) { - this.div.innerHTML = this.html; - } - woosmap.map.event.addDomListener(this.div, "click", () => { - woosmap.map.event.trigger(this, "click"); - }); - } - - private appendDivToOverlay(): void { - const panes = this.getPanes(); - if (panes && this.div) { - panes.floatPane.appendChild(this.div); - } - } - - private positionDiv(): void { - const point = this.getProjection()?.fromLatLngToDivPixel(this.latlng); - if (point && this.div) { - // Offset should depend on the style of your popover - const offsetWidth = this.div.offsetWidth / 2; // 50% of div width - const offsetHeight = this.div.offsetHeight + 6; // Full height of div plus the arrow height - // @ts-ignore - this.div.style.left = `${point.x - offsetWidth}px`; - // @ts-ignore - this.div.style.top = `${point.y - offsetHeight}px`; - } - } - - draw(): void { - this.positionDiv(); - } - - onAdd(): void { - if (!this.div) { - this.createDiv(); - this.appendDivToOverlay(); - } - } - - onRemove(): void { - if (this.div && this.div.parentNode) { - this.div.parentNode.removeChild(this.div); - this.div = null; - } - } - - getPosition(): woosmap.map.LatLng { - return this.latlng; - } - - addEventListener(eventName: string, callback: () => void): void { - if (this.div) { - this.div.addEventListener(eventName, callback); - } - } + return div; } const center: woosmap.map.LatLngLiteral = { lat: 51.5074, lng: -0.1278 }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 13, center: center, - }, - ); + }); const markersData: MarkerData[] = [ { price: "100 €" }, @@ -108,38 +43,28 @@ function initMap(): void { { lat: 51.5074, lng: -0.1078 }, ]; - const markers: HTMLMapMarker[] = []; + const markers: woosmap.map.marker.AdvancedMarkerElement[] = []; markersData.forEach((data, index) => { - const marker = new HTMLMapMarker({ - latlng: new woosmap.map.LatLng( - positions[index].lat, - positions[index].lng, - ), + const content = createMarkerContent(data); + const marker = new woosmap.map.marker.AdvancedMarkerElement({ + position: positions[index], map: map, - data: data, + content, + gmpClickable: true, }); - marker.addEventListener("click", () => { + marker.addListener("click", () => { markers.forEach((m) => { - if (m.div) { - m.div.classList.remove("active"); - } + (m.content as HTMLDivElement).classList.remove("active"); }); - if (marker.div) { - marker.div.classList.add("active"); - } + content.classList.add("active"); }); markers.push(marker); }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_marker_html_css] export {}; diff --git a/samples/marker-html-css/marker-html-css.json b/samples/marker-html-css/marker-html-css.json index 35f16d87..3d70741a 100644 --- a/samples/marker-html-css/marker-html-css.json +++ b/samples/marker-html-css/marker-html-css.json @@ -3,7 +3,7 @@ "description": "Create markers with HTML and CSS", "category": "Markers", "callback": "initMap", - "libraries": [], + "libraries": "marker", "tag": "marker_html_css", "name": "marker-html-css", "pagination": { @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/marker-label/index.njk b/samples/marker-label/index.njk index 25c410dd..6e7d70aa 100644 --- a/samples/marker-label/index.njk +++ b/samples/marker-label/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
      Click on the map to add new MarkerLabel
      -
      + {% endblock %} diff --git a/samples/marker-label/index.ts b/samples/marker-label/index.ts index 1859205b..2d5bd892 100644 --- a/samples/marker-label/index.ts +++ b/samples/marker-label/index.ts @@ -1,52 +1,44 @@ // [START woosmap_marker_label] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; - const iconMarker: woosmap.map.Icon = { - labelOrigin: new window.woosmap.map.Point(14, 15), - url: "https://images.woosmap.com/marker-red.svg", - }; + function createMarkerContent(label: string): HTMLElement { + const { PinElement } = woosmap.map.marker; + return new PinElement({ + background: "#f50057", + glyphText: label, + glyphColor: "#FFFFFF", + }).element; + } - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 10, center: center, - }, - ); + }); // [START woosmap_marker_label_add_label] let labelNumber = 1; - new window.woosmap.map.Marker({ + new woosmap.map.marker.AdvancedMarkerElement({ position: map.getCenter(), - icon: iconMarker, - label: { - text: String(labelNumber), - color: "white", - }, + content: createMarkerContent(String(labelNumber)), map, }); // [END woosmap_marker_label_add_label] map.addListener("click", (e) => { labelNumber += 1; - new window.woosmap.map.Marker({ + new woosmap.map.marker.AdvancedMarkerElement({ position: e.latlng, - icon: iconMarker, - label: { - text: String(labelNumber), - color: "white", - }, + content: createMarkerContent(String(labelNumber)), map, }); }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_marker_label] export {}; diff --git a/samples/marker-label/marker-label.json b/samples/marker-label/marker-label.json index 834f58cb..1d9e8e9d 100644 --- a/samples/marker-label/marker-label.json +++ b/samples/marker-label/marker-label.json @@ -3,7 +3,7 @@ "description": "A Marker Label is a maker with a text label drawn inside it.", "category": "Markers", "callback": "initMap", - "libraries": [], + "libraries": "marker", "tag": "marker_label", "name": "marker-label", "pagination": { @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/marker-simple/index.njk b/samples/marker-simple/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/marker-simple/index.njk +++ b/samples/marker-simple/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
      + {% endblock %} diff --git a/samples/marker-simple/index.ts b/samples/marker-simple/index.ts index bd3c4e39..8f791db6 100644 --- a/samples/marker-simple/index.ts +++ b/samples/marker-simple/index.ts @@ -1,33 +1,31 @@ // [START woosmap_marker_simple] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { - zoom: 13, - center: center, - }, - ); + const map = (document.getElementById("map") as woosmap.map.MapElement) + .innerMap; + map.moveCamera({ + zoom: 13, + center: center, + }); - const marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + const marker = new woosmap.map.marker.AdvancedMarkerElement({ position: map.getCenter(), - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); marker.setMap(map); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_marker_simple] export {}; diff --git a/samples/marker-simple/marker-simple.json b/samples/marker-simple/marker-simple.json index 60978278..4aba504c 100644 --- a/samples/marker-simple/marker-simple.json +++ b/samples/marker-simple/marker-simple.json @@ -3,7 +3,7 @@ "description": "Adding a simple marker on the center of the map", "category": "Markers", "callback": "initMap", - "libraries": [], + "libraries": "marker", "tag": "marker_simple", "name": "marker-simple", "pagination": { @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/multisearch-address-form-autofill/index.ts b/samples/multisearch-address-form-autofill/index.ts index b572cd5f..0c13f43f 100644 --- a/samples/multisearch-address-form-autofill/index.ts +++ b/samples/multisearch-address-form-autofill/index.ts @@ -24,7 +24,24 @@ const searchOptions = { }, }, }; -let multiSearch; +// The MultiSearch JS API ships no typings: describe the parts this sample uses. +interface MultiSearchPrediction { + id: string; + api: string; + description?: string; + highlight: string; +} + +interface MultiSearch { + autocompleteMulti(input: string): Promise; + detailsMulti(request: { id: string; api: string }): Promise; +} + +interface MultiSearchGlobal { + multisearch(options: object): MultiSearch; +} + +let multiSearch: MultiSearch; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; @@ -58,8 +75,7 @@ function init(): void { inputElement.focus(); }); - // @ts-ignore - multiSearch = window.woosmap.multisearch(searchOptions); + multiSearch = (woosmap as unknown as MultiSearchGlobal).multisearch(searchOptions); } function handleAutocomplete(): void { @@ -209,17 +225,6 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - // currently, the MultiSearch JS API typings are not exported, so we use `any` here - // @ts-ignore - woosmap: { - localities: { - multisearch: (defaultSearchOptions: any) => any; - }; - }; - } -} // [END woosmap_multisearch_address_form_autofill] export {}; diff --git a/samples/multisearch-js-api/index.ts b/samples/multisearch-js-api/index.ts index cf1a1cae..e2524c36 100644 --- a/samples/multisearch-js-api/index.ts +++ b/samples/multisearch-js-api/index.ts @@ -17,7 +17,24 @@ const searchOptions = { minInputLength: 6, }, }; -let multiSearch; +// The MultiSearch JS API ships no typings: describe the parts this sample uses. +interface MultiSearchPrediction { + id: string; + api: string; + description?: string; + highlight: string; +} + +interface MultiSearch { + autocompleteMulti(input: string): Promise; + detailsMulti(request: { id: string; api: string }): Promise; +} + +interface MultiSearchGlobal { + multisearch(options: object): MultiSearch; +} + +let multiSearch: MultiSearch; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; @@ -43,8 +60,7 @@ function init(): void { inputElement.focus(); }); - // @ts-ignore - multiSearch = window.woosmap.multisearch(searchOptions); + multiSearch = (woosmap as unknown as MultiSearchGlobal).multisearch(searchOptions); } function handleAutocomplete(): void { @@ -140,17 +156,6 @@ document.addEventListener("DOMContentLoaded", () => { init(); }); -declare global { - interface Window { - // currently, the MultiSearch JS API typings are not exported, so we use `any` here - // @ts-ignore - woosmap: { - localities: { - multisearch: (defaultSearchOptions: any) => any; - }; - }; - } -} // [END woosmap_multisearch_js_api] export {}; diff --git a/samples/multisearch-map-advanced/index.njk b/samples/multisearch-map-advanced/index.njk index 75533c41..0c4f74cc 100644 --- a/samples/multisearch-map-advanced/index.njk +++ b/samples/multisearch-map-advanced/index.njk @@ -18,7 +18,7 @@
        -
        + {% endblock %} diff --git a/samples/multisearch-map-advanced/index.ts b/samples/multisearch-map-advanced/index.ts index 5861badf..484e6c3d 100644 --- a/samples/multisearch-map-advanced/index.ts +++ b/samples/multisearch-map-advanced/index.ts @@ -31,12 +31,29 @@ const searchOptions = { }, }, }; -let multiSearch; +// The MultiSearch JS API ships no typings: describe the parts this sample uses. +interface MultiSearchPrediction { + id: string; + api: string; + description?: string; + highlight: string; +} + +interface MultiSearch { + autocompleteMulti(input: string): Promise; + detailsMulti(request: { id: string; api: string }): Promise; +} + +interface MultiSearchGlobal { + multisearch(options: object): MultiSearch; +} + +let multiSearch: MultiSearch; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; let map: woosmap.map.Map; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; let infoWindow: woosmap.map.InfoWindow; function initSearch(): void { @@ -73,18 +90,18 @@ function initSearch(): void { inputElement.focus(); }); - // @ts-ignore - multiSearch = window.woosmap.multisearch(searchOptions); + multiSearch = (woosmap as unknown as MultiSearchGlobal).multisearch(searchOptions); } -function initMap(): void { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.50940214, lng: -0.133012 }, zoom: 4, - }, - ); + }); infoWindow = new woosmap.map.InfoWindow({}); initSearch(); } @@ -150,15 +167,17 @@ function formatPredictionList(result): string { } function createMarker(result) { - return new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + return new woosmap.map.marker.AdvancedMarkerElement({ position: result.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, + gmpClickable: true, }); } @@ -189,12 +208,12 @@ function displayLocality(result, apiName: string) { infoWindow.setOffset(new woosmap.map.Point(0, -50)); infoWindow.setContent(infoWindowHTML); marker.addListener("click", () => { - infoWindow.open(map, marker.getPosition()); + infoWindow.open({map, anchor: marker}); }); map.setCenter(result.geometry.location, { top: 150 }); map.setZoom(14); woosmap.map.event.addListenerOnce(map, "idle", () => { - infoWindow.open(map, marker.position); + infoWindow.open({map, anchor: marker}); }); } } @@ -210,12 +229,7 @@ document.addEventListener("click", (event) => { } }); -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_multisearch_map_advanced] export {}; diff --git a/samples/multisearch-map-advanced/multisearch-map-advanced.json b/samples/multisearch-map-advanced/multisearch-map-advanced.json index 2f107d57..5fb80765 100644 --- a/samples/multisearch-map-advanced/multisearch-map-advanced.json +++ b/samples/multisearch-map-advanced/multisearch-map-advanced.json @@ -11,5 +11,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/multisearch-map-simple/index.njk b/samples/multisearch-map-simple/index.njk index 75533c41..0c4f74cc 100644 --- a/samples/multisearch-map-simple/index.njk +++ b/samples/multisearch-map-simple/index.njk @@ -18,7 +18,7 @@
          -
          + {% endblock %} diff --git a/samples/multisearch-map-simple/index.ts b/samples/multisearch-map-simple/index.ts index 53b0c828..cf584af8 100644 --- a/samples/multisearch-map-simple/index.ts +++ b/samples/multisearch-map-simple/index.ts @@ -14,12 +14,29 @@ const searchOptions = { minInputLength: 5, }, }; -let multiSearch; +// The MultiSearch JS API ships no typings: describe the parts this sample uses. +interface MultiSearchPrediction { + id: string; + api: string; + description?: string; + highlight: string; +} + +interface MultiSearch { + autocompleteMulti(input: string): Promise; + detailsMulti(request: { id: string; api: string }): Promise; +} + +interface MultiSearchGlobal { + multisearch(options: object): MultiSearch; +} + +let multiSearch: MultiSearch; let inputElement: HTMLInputElement; let suggestionsList: HTMLUListElement; let clearSearchBtn: HTMLButtonElement; let map: woosmap.map.Map; -let marker: woosmap.map.Marker; +let marker: woosmap.map.marker.AdvancedMarkerElement; function initSearch(): void { inputElement = document.getElementById( @@ -52,18 +69,18 @@ function initSearch(): void { inputElement.focus(); }); - // @ts-ignore - multiSearch = window.woosmap.multisearch(searchOptions); + multiSearch = (woosmap as unknown as MultiSearchGlobal).multisearch(searchOptions); } -function initMap(): void { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.50940214, lng: -0.133012 }, zoom: 4, - }, - ); + }); initSearch(); } @@ -131,15 +148,16 @@ function displayLocality(result) { marker.setMap(null); } if (result?.geometry) { - marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + marker = new woosmap.map.marker.AdvancedMarkerElement({ position: result.geometry.location, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); marker.setMap(map); map.flyTo({ center: result.geometry.location, zoom: 14 }); @@ -157,12 +175,7 @@ document.addEventListener("click", (event) => { } }); -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_multisearch_map_simple] export {}; diff --git a/samples/multisearch-map-simple/multisearch-map-simple.json b/samples/multisearch-map-simple/multisearch-map-simple.json index 1c67341f..94e6f023 100644 --- a/samples/multisearch-map-simple/multisearch-map-simple.json +++ b/samples/multisearch-map-simple/multisearch-map-simple.json @@ -11,5 +11,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/react-map-basic/index.tsx b/samples/react-map-basic/index.tsx index 735b7c15..aa151138 100644 --- a/samples/react-map-basic/index.tsx +++ b/samples/react-map-basic/index.tsx @@ -9,27 +9,65 @@ import React, { useState, } from "react"; -// Define the types for the global Woosmap object -declare const woosmap: any; +// The shim reads and writes `window.woosmap` before the API is loaded. +type LoaderWindow = { + woosmap?: { + map?: Record unknown>; + }; +}; + +const WOOSMAP_SDK_HOST = "https://sdk.woosmap.com"; + +// Installs the documented Woosmap loader shim (see docs/docs/loader.md), which +// defines a stub `woosmap.map.importLibrary` that fetches map.js on first call. +// Safe to call more than once: the shim itself no-ops (and warns) past the first. +function installLoaderShim(apiKey: string): void { + ((g) => { + let p; + const w = window as unknown as LoaderWindow, + d = document; + const L = "importLibrary", + CB = "__ib__"; + const E = "The Woosmap Maps JavaScript API"; + const woosmap = w.woosmap || (w.woosmap = {}); + const maps = woosmap.map || (woosmap.map = {}); + const libs = new Set(), + params = new URLSearchParams(); + const load = () => + p || + (p = new Promise((res, rej) => { + const s = d.createElement("script"); + params.set("libraries", [...libs].join(",")); + for (const k in g) params.set(k, g[k]); + params.set("callback", "woosmap.map." + CB); + s.src = `${WOOSMAP_SDK_HOST}/map/map.js?` + params; + maps[CB] = res; + s.onerror = () => rej(Error(E + " could not load.")); + d.head.append(s); + })); + if (maps[L]) { + console.warn(E + " only loads once. Ignoring:", g); + } else { + maps[L] = (name: string, ...args: unknown[]) => + libs.add(name) && load().then(() => maps[L](name, ...args)); + } + })({ key: apiKey }); +} -// Custom hook to load the Woosmap JavaScript API -// This hook creates a script tag with the Woosmap map.js URL and appends it to the body of the document. -// It sets the state to true when the script loads. +// Custom hook to load the Woosmap JavaScript API via the loader shim. function useWoosmap(apiKey: string) { const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { - const script = document.createElement("script"); - script.src = `https://sdk.woosmap.com/map/map.js?key=${apiKey}`; - script.onload = () => setIsLoaded(true); - document.body.appendChild(script); + installLoaderShim(apiKey); + woosmap.map.importLibrary("maps").then(() => setIsLoaded(true)); }, [apiKey]); return isLoaded; } // Contexts for Woosmap library -const MapContext = createContext(null); +const MapContext = createContext(null); interface WoosmapAPIProviderProps { apiKey: string; @@ -88,6 +126,6 @@ window.addEventListener("DOMContentLoaded", () => { }); // [END woosmap_react_map_basic] -let PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +let PRESERVE_COMMENT_ABOVE; // eslint-disable-line @typescript-eslint/no-unused-vars -- force tsc to maintain the comment above export {}; diff --git a/samples/react-map-with-custom-overlay/index.tsx b/samples/react-map-with-custom-overlay/index.tsx index 0f13b589..d9d73d37 100644 --- a/samples/react-map-with-custom-overlay/index.tsx +++ b/samples/react-map-with-custom-overlay/index.tsx @@ -8,25 +8,65 @@ import React, { useState, } from "react"; -// Define the types for the global Woosmap object -declare const woosmap: any; +// The shim reads and writes `window.woosmap` before the API is loaded. +type LoaderWindow = { + woosmap?: { + map?: Record unknown>; + }; +}; + +const WOOSMAP_SDK_HOST = "https://sdk.woosmap.com"; + +// Installs the documented Woosmap loader shim (see docs/docs/loader.md), which +// defines a stub `woosmap.map.importLibrary` that fetches map.js on first call. +// Safe to call more than once: the shim itself no-ops (and warns) past the first. +function installLoaderShim(apiKey: string): void { + ((g) => { + let p; + const w = window as unknown as LoaderWindow, + d = document; + const L = "importLibrary", + CB = "__ib__"; + const E = "The Woosmap Maps JavaScript API"; + const woosmap = w.woosmap || (w.woosmap = {}); + const maps = woosmap.map || (woosmap.map = {}); + const libs = new Set(), + params = new URLSearchParams(); + const load = () => + p || + (p = new Promise((res, rej) => { + const s = d.createElement("script"); + params.set("libraries", [...libs].join(",")); + for (const k in g) params.set(k, g[k]); + params.set("callback", "woosmap.map." + CB); + s.src = `${WOOSMAP_SDK_HOST}/map/map.js?` + params; + maps[CB] = res; + s.onerror = () => rej(Error(E + " could not load.")); + d.head.append(s); + })); + if (maps[L]) { + console.warn(E + " only loads once. Ignoring:", g); + } else { + maps[L] = (name: string, ...args: unknown[]) => + libs.add(name) && load().then(() => maps[L](name, ...args)); + } + })({ key: apiKey }); +} -// Custom hook to load the Woosmap JavaScript API +// Custom hook to load the Woosmap JavaScript API via the loader shim. function useWoosmap(apiKey: string) { const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { - const script = document.createElement("script"); - script.src = `https://sdk.woosmap.com/map/map.js?key=${apiKey}`; - script.onload = () => setIsLoaded(true); - document.body.appendChild(script); + installLoaderShim(apiKey); + woosmap.map.importLibrary("maps").then(() => setIsLoaded(true)); }, [apiKey]); return isLoaded; } // Contexts for Woosmap and the map instance -const MapContext = createContext(null); +const MapContext = createContext(null); const MapInstanceContext = createContext(null); interface WoosmapAPIProviderProps { @@ -126,12 +166,15 @@ const Marker: React.FC<{ }> = ({ position, icon }) => { const woosmap = useContext(MapContext); const mapInstance = useContext(MapInstanceContext); - const [overlay, setOverlay] = useState(null); + const [overlay, setOverlay] = useState( + null, + ); useEffect(() => { if (!woosmap || !mapInstance || !position) return; - class CustomOverlay extends (woosmap.map.OverlayView as new () => any) { + class CustomOverlay extends (woosmap.map + .OverlayView as new () => woosmap.map.OverlayView) { private position: woosmap.map.LatLngLiteral; private containerDiv: HTMLDivElement; private icon: React.ReactNode; @@ -147,16 +190,17 @@ const Marker: React.FC<{ onAdd() { const root = createRoot(this.containerDiv); root.render(this.icon); - const panes = this.getPanes(); - panes.floatPane.appendChild(this.containerDiv); + this.getPanes()?.floatPane.appendChild(this.containerDiv); this.addEventListener("click", () => { alert("Marker clicked!"); }); } draw() { - const projection = this.getProjection(); - const point = projection.fromLatLngToDivPixel(this.position); + // @types/woosmap.map does not declare Point's x/y yet. + const point = this.getProjection()?.fromLatLngToDivPixel( + this.position, + ) as { x: number; y: number } | null | undefined; if (point) { // Offset should depend on the style of your icon - here it is positioned at the middle const offsetWidth = this.containerDiv.offsetWidth / 2; // 50% of div width @@ -226,6 +270,6 @@ window.addEventListener("DOMContentLoaded", () => { }); // [END woosmap_react_map_with_custom_overlay] -let PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +let PRESERVE_COMMENT_ABOVE; // eslint-disable-line @typescript-eslint/no-unused-vars -- force tsc to maintain the comment above export {}; diff --git a/samples/react-map-with-localities/index.tsx b/samples/react-map-with-localities/index.tsx index cc84741e..25decea9 100644 --- a/samples/react-map-with-localities/index.tsx +++ b/samples/react-map-with-localities/index.tsx @@ -9,27 +9,68 @@ import React, { useState, } from "react"; -// Define the types for the global Woosmap object -declare const woosmap: any; +// The shim reads and writes `window.woosmap` before the API is loaded. +type LoaderWindow = { + woosmap?: { + map?: Record unknown>; + }; +}; -// Custom hook to load the Woosmap JavaScript API -// This hook creates a script tag with the Woosmap map.js URL and appends it to the body of the document. -// It sets the state to true when the script loads. +const WOOSMAP_SDK_HOST = "https://sdk.woosmap.com"; + +// Installs the documented Woosmap loader shim (see docs/docs/loader.md), which +// defines a stub `woosmap.map.importLibrary` that fetches map.js on first call. +// Safe to call more than once: the shim itself no-ops (and warns) past the first. +function installLoaderShim(apiKey: string): void { + ((g) => { + let p; + const w = window as unknown as LoaderWindow, + d = document; + const L = "importLibrary", + CB = "__ib__"; + const E = "The Woosmap Maps JavaScript API"; + const woosmap = w.woosmap || (w.woosmap = {}); + const maps = woosmap.map || (woosmap.map = {}); + const libs = new Set(), + params = new URLSearchParams(); + const load = () => + p || + (p = new Promise((res, rej) => { + const s = d.createElement("script"); + params.set("libraries", [...libs].join(",")); + for (const k in g) params.set(k, g[k]); + params.set("callback", "woosmap.map." + CB); + s.src = `${WOOSMAP_SDK_HOST}/map/map.js?` + params; + maps[CB] = res; + s.onerror = () => rej(Error(E + " could not load.")); + d.head.append(s); + })); + if (maps[L]) { + console.warn(E + " only loads once. Ignoring:", g); + } else { + maps[L] = (name: string, ...args: unknown[]) => + libs.add(name) && load().then(() => maps[L](name, ...args)); + } + })({ key: apiKey }); +} + +// Custom hook to load the Woosmap JavaScript API via the loader shim. function useWoosmap(apiKey: string) { const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { - const script = document.createElement("script"); - script.src = `https://sdk.woosmap.com/map/map.js?key=${apiKey}`; - script.onload = () => setIsLoaded(true); - document.body.appendChild(script); + installLoaderShim(apiKey); + Promise.all([ + woosmap.map.importLibrary("maps"), + woosmap.map.importLibrary("marker"), + ]).then(() => setIsLoaded(true)); }, [apiKey]); return isLoaded; } // Contexts for Woosmap and the map instance -const MapContext = createContext(null); +const MapContext = createContext(null); const MapInstanceContext = createContext(null); interface WoosmapAPIProviderProps { @@ -81,10 +122,13 @@ const WoosmapMap: React.FC = ({ center, zoom, children }) => { }; // This component creates a Woosmap marker to display the selected locality and flyTo it -const Marker: React.FC = ({ position }) => { +const Marker: React.FC = ({ + position, +}) => { const woosmap = useContext(MapContext); const mapInstance = useContext(MapInstanceContext); - const [marker, setMarker] = useState(null); + const [marker, setMarker] = + useState(null); useEffect(() => { if (marker) { @@ -92,15 +136,16 @@ const Marker: React.FC = ({ position }) => { setMarker(null); } if (mapInstance && position) { - const localityMarker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + const localityMarker = new woosmap.map.marker.AdvancedMarkerElement({ position, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); localityMarker.setMap(mapInstance); setMarker(localityMarker); @@ -253,6 +298,6 @@ window.addEventListener("DOMContentLoaded", () => { }); // [END woosmap_react_map_with_localities] -let PRESERVE_COMMENT_ABOVE; // force tsc to maintain the comment above eslint-disable-line +let PRESERVE_COMMENT_ABOVE; // eslint-disable-line @typescript-eslint/no-unused-vars -- force tsc to maintain the comment above export {}; diff --git a/samples/render-shapes-circles/index.njk b/samples/render-shapes-circles/index.njk index f2ff4535..6150b04a 100644 --- a/samples/render-shapes-circles/index.njk +++ b/samples/render-shapes-circles/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
          + {% endblock %} diff --git a/samples/render-shapes-circles/index.ts b/samples/render-shapes-circles/index.ts index 7b63aa3b..72be01e9 100644 --- a/samples/render-shapes-circles/index.ts +++ b/samples/render-shapes-circles/index.ts @@ -135,8 +135,11 @@ const data = { ], }; -function initMap() { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 40, lng: 0, @@ -160,7 +163,7 @@ function initMap() { }); } } -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_circles] export {}; diff --git a/samples/render-shapes-circles/render-shapes-circles.json b/samples/render-shapes-circles/render-shapes-circles.json index 429ff35c..23bbffaa 100644 --- a/samples/render-shapes-circles/render-shapes-circles.json +++ b/samples/render-shapes-circles/render-shapes-circles.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/render-shapes-data-events/index.njk b/samples/render-shapes-data-events/index.njk index 0fc3a07e..51b536e4 100644 --- a/samples/render-shapes-data-events/index.njk +++ b/samples/render-shapes-data-events/index.njk @@ -1,7 +1,7 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
          -
          +
          {% endblock %} diff --git a/samples/render-shapes-data-events/index.ts b/samples/render-shapes-data-events/index.ts index d94214a0..da7aa9a8 100644 --- a/samples/render-shapes-data-events/index.ts +++ b/samples/render-shapes-data-events/index.ts @@ -35,14 +35,14 @@ function setupListener(name) { } } -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 29.65, lng: -97.74 }, zoom: 6, - }, - ); + }); //Outter Shape of Polygon const outerShape = [ { lat: 28.59, lng: -100.65 }, @@ -75,12 +75,7 @@ function initMap() { } } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_data_events] export {}; diff --git a/samples/render-shapes-data-events/render-shapes-data-events.json b/samples/render-shapes-data-events/render-shapes-data-events.json index 248cc1e0..1e10a9da 100644 --- a/samples/render-shapes-data-events/render-shapes-data-events.json +++ b/samples/render-shapes-data-events/render-shapes-data-events.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/render-shapes-data/index.njk b/samples/render-shapes-data/index.njk index ca9326f2..aa5ac590 100644 --- a/samples/render-shapes-data/index.njk +++ b/samples/render-shapes-data/index.njk @@ -2,5 +2,5 @@ {% block html %}
          Click on a Pub...
          -
          + {% endblock %} diff --git a/samples/render-shapes-data/index.ts b/samples/render-shapes-data/index.ts index 05f60c3b..5262c2b0 100644 --- a/samples/render-shapes-data/index.ts +++ b/samples/render-shapes-data/index.ts @@ -198,18 +198,18 @@ const pubsData = { ], }; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 53.3430183, lng: -6.25321 }, zoom: 14, - }, - ); + }); pubsData.pubs.forEach((pub) => { map.data.add({ - geometry: new window.woosmap.map.Data.Point({ + geometry: new woosmap.map.Data.Point({ lat: pub.coordinates[1], lng: pub.coordinates[0], }), @@ -248,12 +248,7 @@ function initMap() { }); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_data] export {}; diff --git a/samples/render-shapes-data/render-shapes-data.json b/samples/render-shapes-data/render-shapes-data.json index 6c12c5e3..3a4b2dc0 100644 --- a/samples/render-shapes-data/render-shapes-data.json +++ b/samples/render-shapes-data/render-shapes-data.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/render-shapes-geojson/index.njk b/samples/render-shapes-geojson/index.njk index f2ff4535..6150b04a 100644 --- a/samples/render-shapes-geojson/index.njk +++ b/samples/render-shapes-geojson/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
          + {% endblock %} diff --git a/samples/render-shapes-geojson/index.ts b/samples/render-shapes-geojson/index.ts index 7b19e2d4..a0062627 100644 --- a/samples/render-shapes-geojson/index.ts +++ b/samples/render-shapes-geojson/index.ts @@ -2,14 +2,14 @@ // Initialize and add the map let map: woosmap.map.Map; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 53.51, lng: 8.15 }, zoom: 4, - }, - ); + }); map.data.loadGeoJson( "https://demo.woosmap.com/misc/data/europe.geojson.json", @@ -48,12 +48,7 @@ function initMap() { } } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_geojson] export {}; diff --git a/samples/render-shapes-geojson/render-shapes-geojson.json b/samples/render-shapes-geojson/render-shapes-geojson.json index ccd263d5..3f1aa8ec 100644 --- a/samples/render-shapes-geojson/render-shapes-geojson.json +++ b/samples/render-shapes-geojson/render-shapes-geojson.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/render-shapes-polygons/index.njk b/samples/render-shapes-polygons/index.njk index f2ff4535..6150b04a 100644 --- a/samples/render-shapes-polygons/index.njk +++ b/samples/render-shapes-polygons/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
          + {% endblock %} diff --git a/samples/render-shapes-polygons/index.ts b/samples/render-shapes-polygons/index.ts index 6761ca7a..e387c2d1 100644 --- a/samples/render-shapes-polygons/index.ts +++ b/samples/render-shapes-polygons/index.ts @@ -2,15 +2,15 @@ // Initialize and add the map let map: woosmap.map.Map; -function initMap() { +async function initMap() { + await woosmap.map.importLibrary("maps"); + // [START woosmap_add_map_instantiate_map] - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 29.65, lng: -97.74 }, zoom: 6, - }, - ); + }); // [END woosmap_add_map_instantiate_map] //Outter Shape of Polygon const outerShape = [ @@ -40,12 +40,7 @@ function initMap() { polygon.setMap(map); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_polygons] export {}; diff --git a/samples/render-shapes-polygons/render-shapes-polygons.json b/samples/render-shapes-polygons/render-shapes-polygons.json index 0c814683..5ea6d220 100644 --- a/samples/render-shapes-polygons/render-shapes-polygons.json +++ b/samples/render-shapes-polygons/render-shapes-polygons.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/render-shapes-polylines/index.njk b/samples/render-shapes-polylines/index.njk index f2ff4535..6150b04a 100644 --- a/samples/render-shapes-polylines/index.njk +++ b/samples/render-shapes-polylines/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
          + {% endblock %} diff --git a/samples/render-shapes-polylines/index.ts b/samples/render-shapes-polylines/index.ts index 5995ebc4..197c5bbd 100644 --- a/samples/render-shapes-polylines/index.ts +++ b/samples/render-shapes-polylines/index.ts @@ -2,14 +2,14 @@ // Initialize and add the map let map: woosmap.map.Map; -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { +async function initMap() { + await woosmap.map.importLibrary("maps"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 51.505, lng: -0.118 }, zoom: 15, - }, - ); + }); //Polyline Shape const polylinePath = [ { lng: -0.12638568878173828, lat: 51.50099581189912 }, @@ -39,7 +39,7 @@ function initMap() { }); polyline.setMap(map); } -window.initMap = initMap; +initMap(); // [END woosmap_render_shapes_polylines] export {}; diff --git a/samples/render-shapes-polylines/render-shapes-polylines.json b/samples/render-shapes-polylines/render-shapes-polylines.json index 7342e8c5..e9ba6ad1 100644 --- a/samples/render-shapes-polylines/render-shapes-polylines.json +++ b/samples/render-shapes-polylines/render-shapes-polylines.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/samples.11tydata.js b/samples/samples.11tydata.js index 69fac1c1..4a8835c1 100644 --- a/samples/samples.11tydata.js +++ b/samples/samples.11tydata.js @@ -4,9 +4,10 @@ const data = { ..._.pick( { WOOSMAP_PUBLIC_API_KEY: "woos-e1e5490b-19d1-34f8-9955-fd5cfc8c880f", + WOOSMAP_SDK_HOST: "https://sdk.woosmap.com", ...process.env, }, - ["WOOSMAP_PUBLIC_API_KEY"], + ["WOOSMAP_PUBLIC_API_KEY", "WOOSMAP_SDK_HOST"], ), libraries: [], mode: ["jsfiddle", "docs", "app", "highlight"], diff --git a/samples/store-locator-widget-baidu/index.ts b/samples/store-locator-widget-baidu/index.ts index bc33909a..66edd9a6 100644 --- a/samples/store-locator-widget-baidu/index.ts +++ b/samples/store-locator-widget-baidu/index.ts @@ -62,9 +62,13 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget_baidu] diff --git a/samples/store-locator-widget-custom-filters/index.ts b/samples/store-locator-widget-custom-filters/index.ts index 0886f9bc..71d7b3e5 100644 --- a/samples/store-locator-widget-custom-filters/index.ts +++ b/samples/store-locator-widget-custom-filters/index.ts @@ -154,9 +154,19 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + setFilterPanelRenderer( + renderer: (title: string, children: HTMLElement[]) => HTMLElement, + ): void; + setFilterRenderer( + renderer: (key: string, label: string, selected: boolean) => HTMLElement, + ): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget_custom_filters] diff --git a/samples/store-locator-widget-custom-renderer/index.ts b/samples/store-locator-widget-custom-renderer/index.ts index b551c87f..483f6428 100644 --- a/samples/store-locator-widget-custom-renderer/index.ts +++ b/samples/store-locator-widget-custom-renderer/index.ts @@ -117,7 +117,7 @@ function getFullSchedule({ const daysHoursHTMLTable = Object.keys(dayLabels) .map((day) => { const hours = weeklyOpening[day]?.hours || []; - let daysHours = ""; + let daysHours: string; if (hours.length === 0) { daysHours = "Closed"; @@ -155,7 +155,6 @@ function getOpeningLabel({ if (properties.open.open_now) { openLabel = `Open now until ${properties.open.current_slice?.end}`; } else { - // @ts-ignore - TODO next_opening is wrongly spelled `nextOpening` in @types/woosmap.map openLabel = `Closed until ${convertTime(Date.parse(properties.open.next_opening?.day || "") / 1000)} at ${properties.open.next_opening?.start}`; } @@ -218,9 +217,20 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + setFullStoreRenderer( + renderer: (store: woosmap.map.stores.StoreResponse) => HTMLElement, + ): void; + setSummaryStoreRenderer( + renderer: (store: woosmap.map.stores.StoreResponse) => HTMLElement, + ): void; + setInitialStateToSelectedStore(storeId: string): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget_custom_renderer] diff --git a/samples/store-locator-widget-enforce-accessibility/index.ts b/samples/store-locator-widget-enforce-accessibility/index.ts index 14215b86..b4a6cd64 100644 --- a/samples/store-locator-widget-enforce-accessibility/index.ts +++ b/samples/store-locator-widget-enforce-accessibility/index.ts @@ -586,9 +586,13 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget_enforce_accessibility] diff --git a/samples/store-locator-widget-events/index.ts b/samples/store-locator-widget-events/index.ts index bb8e77e7..007fded1 100644 --- a/samples/store-locator-widget-events/index.ts +++ b/samples/store-locator-widget-events/index.ts @@ -129,9 +129,15 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + HANDLED_EVENT: Record; + listenOn(event: string, callback: (...args: unknown[]) => void): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget_events] diff --git a/samples/store-locator-widget/index.ts b/samples/store-locator-widget/index.ts index 57c8e13d..d224a2ae 100644 --- a/samples/store-locator-widget/index.ts +++ b/samples/store-locator-widget/index.ts @@ -585,9 +585,13 @@ function initStoreLocator(): void { initStoreLocator(); declare global { - // currently, the WebApp typings are not exported, so we use `any` here + // The store locator widget ships no typings: declare the parts this sample uses. + interface StoreLocatorWebApp { + setConf(conf: object): void; + render(isMobile: boolean): void; + } interface Window { - WebApp: new (elementId: string, projectKey: string) => any; + WebApp: new (elementId: string, projectKey: string) => StoreLocatorWebApp; } } // [END woosmap_store_locator_widget] diff --git a/samples/stores-list-sync-map/index.njk b/samples/stores-list-sync-map/index.njk index 6731bfd9..7185d5a4 100644 --- a/samples/stores-list-sync-map/index.njk +++ b/samples/stores-list-sync-map/index.njk @@ -23,7 +23,7 @@ -
          + {% endblock %} diff --git a/samples/stores-list-sync-map/index.ts b/samples/stores-list-sync-map/index.ts index 89518b67..15299c22 100644 --- a/samples/stores-list-sync-map/index.ts +++ b/samples/stores-list-sync-map/index.ts @@ -1,6 +1,6 @@ // [START woosmap_stores_list_sync_map] let map: woosmap.map.Map; -let activeLocation: woosmap.map.Marker | null = null; +let activeLocation: woosmap.map.marker.AdvancedMarkerElement | null = null; let storesOverlay: woosmap.map.StoresOverlay; let storesService: woosmap.map.StoresService; let localitiesService: woosmap.map.LocalitiesService; @@ -24,11 +24,6 @@ const storesStyle: woosmap.map.Style = { }; const mapOptions: woosmap.map.MapOptions = { - zoom: 5, - center: { - lat: 46.5, - lng: 1.4, - }, styles: [{ featureType: "all", stylers: [{ saturation: -100 }] }], }; @@ -178,7 +173,9 @@ function handleGeocodeResults( localities: woosmap.map.localities.LocalitiesGeocodeResponse, ) { const location = localities.results[0]?.geometry?.location; - location && handleSearchResults(location); + if (location) { + handleSearchResults(location); + } } function handleSearchResults(originalLatLng: woosmap.map.LatLngLiteral) { @@ -187,19 +184,19 @@ function handleSearchResults(originalLatLng: woosmap.map.LatLngLiteral) { } if (originalLatLng) { - activeLocation = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + activeLocation = new woosmap.map.marker.AdvancedMarkerElement({ position: originalLatLng, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); activeLocation.setMap(map); - map.setCenter(originalLatLng); - map.setZoom(8); + map.moveCamera({ center: originalLatLng, zoom: 8 }); } } @@ -226,19 +223,24 @@ function selectStoreOnList(storeId?: string) { } // Debounce function -function debounce(func: (...args: any[]) => void, wait: number) { +function debounce( + func: (...args: Args) => void, + wait: number, +) { let timeout: ReturnType; - return (...args: any[]) => { + return (...args: Args) => { clearTimeout(timeout); timeout = setTimeout(() => func(...args), wait); }; } -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - mapOptions, - ); +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions(mapOptions); + map.moveCamera({ center: { lat: 46.5, lng: 1.4 }, zoom: 5 }); storesOverlay = new woosmap.map.StoresOverlay(storesStyle); storesOverlay.setMap(map); map.addListener( @@ -249,14 +251,14 @@ function initMap() { displayListStores(visibleStores); }, 50), ); - window.woosmap.map.event.addListener( + woosmap.map.event.addListener( map, "store_selected", (store: woosmap.map.stores.StoreResponse) => { selectStoreOnList(store.properties.store_id); }, ); - window.woosmap.map.event.addListener(map, "store_unselected", () => { + woosmap.map.event.addListener(map, "store_unselected", () => { selectStoreOnList(); }); @@ -273,12 +275,7 @@ function handleError(error: woosmap.map.errors.APIError) { console.error("Error:", error); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_list_sync_map] export {}; diff --git a/samples/stores-list-sync-map/stores-list-sync-map.json b/samples/stores-list-sync-map/stores-list-sync-map.json index 4be0f863..376361eb 100644 --- a/samples/stores-list-sync-map/stores-list-sync-map.json +++ b/samples/stores-list-sync-map/stores-list-sync-map.json @@ -11,5 +11,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/stores-overlay-click-event/index.njk b/samples/stores-overlay-click-event/index.njk index 417b72a5..ffb3940e 100644 --- a/samples/stores-overlay-click-event/index.njk +++ b/samples/stores-overlay-click-event/index.njk @@ -1,5 +1,5 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %}
          Click on a marker to display attributes here
          -
          + {% endblock %} diff --git a/samples/stores-overlay-click-event/index.ts b/samples/stores-overlay-click-event/index.ts index aee87f65..d4b258b1 100644 --- a/samples/stores-overlay-click-event/index.ts +++ b/samples/stores-overlay-click-event/index.ts @@ -1,5 +1,7 @@ // [START woosmap_stores_overlay_click_event] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; const style: woosmap.map.Style = { @@ -26,20 +28,18 @@ function initMap(): void { }, }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 13, center: center, - }, - ); + }); const storesOverlay = new woosmap.map.StoresOverlay(style); storesOverlay.setMap(map); // [START woosmap_stores_overlay_click_event_listener] // Configure the click listener. - window.woosmap.map.event.addListener( + woosmap.map.event.addListener( map, "store_selected", (storeGeoJSON: woosmap.map.stores.StoreResponse) => { @@ -64,11 +64,6 @@ function initMap(): void { // [END woosmap_stores_overlay_click_event_listener] } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_overlay_click_event] export {}; diff --git a/samples/stores-overlay-click-event/stores-overlay-click-event.json b/samples/stores-overlay-click-event/stores-overlay-click-event.json index 2b143ca0..4b9189d0 100644 --- a/samples/stores-overlay-click-event/stores-overlay-click-event.json +++ b/samples/stores-overlay-click-event/stores-overlay-click-event.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/stores-overlay-query-advanced/index.njk b/samples/stores-overlay-query-advanced/index.njk index d950cc87..45b78cab 100644 --- a/samples/stores-overlay-query-advanced/index.njk +++ b/samples/stores-overlay-query-advanced/index.njk @@ -47,5 +47,5 @@ -
          + {% endblock %} \ No newline at end of file diff --git a/samples/stores-overlay-query-advanced/index.ts b/samples/stores-overlay-query-advanced/index.ts index b866dff8..6d0538bc 100644 --- a/samples/stores-overlay-query-advanced/index.ts +++ b/samples/stores-overlay-query-advanced/index.ts @@ -31,7 +31,9 @@ function setQuery() { storesOverlay.setQuery(query.toString()); } -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; const icon: woosmap.map.Icon = { url: "https://images.woosmap.com/marker-blue.svg", @@ -83,13 +85,11 @@ function initMap(): void { }, }, }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 8, center: center, - }, - ); + }); storesOverlay = new woosmap.map.StoresOverlay(style); storesOverlay.setMap(map); @@ -109,11 +109,6 @@ function initUI() { clauseOr.addEventListener("change", setQuery); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_overlay_query_advanced] export {}; diff --git a/samples/stores-overlay-query-advanced/stores-overlay-query-advanced.json b/samples/stores-overlay-query-advanced/stores-overlay-query-advanced.json index f8251f95..82f923ef 100644 --- a/samples/stores-overlay-query-advanced/stores-overlay-query-advanced.json +++ b/samples/stores-overlay-query-advanced/stores-overlay-query-advanced.json @@ -12,5 +12,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/stores-overlay-query/index.njk b/samples/stores-overlay-query/index.njk index b6b1a5d5..e2f84917 100644 --- a/samples/stores-overlay-query/index.njk +++ b/samples/stores-overlay-query/index.njk @@ -7,5 +7,5 @@
          -
          + {% endblock %} diff --git a/samples/stores-overlay-query/index.ts b/samples/stores-overlay-query/index.ts index cd5bf01d..cb0d35ff 100644 --- a/samples/stores-overlay-query/index.ts +++ b/samples/stores-overlay-query/index.ts @@ -1,5 +1,7 @@ // [START woosmap_stores_overlay_query] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; const style: woosmap.map.Style = { @@ -26,13 +28,11 @@ function initMap(): void { }, }; - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 8, center: center, - }, - ); + }); const storesOverlay = new woosmap.map.StoresOverlay(style); storesOverlay.setMap(map); @@ -49,11 +49,6 @@ function initMap(): void { // [END woosmap_stores_overlay_query_set_query] } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_overlay_query] export {}; diff --git a/samples/stores-overlay-query/stores-overlay-query.json b/samples/stores-overlay-query/stores-overlay-query.json index 86be0218..51d31da4 100644 --- a/samples/stores-overlay-query/stores-overlay-query.json +++ b/samples/stores-overlay-query/stores-overlay-query.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/stores-overlay/index.njk b/samples/stores-overlay/index.njk index ad07059d..ccbcaeaf 100644 --- a/samples/stores-overlay/index.njk +++ b/samples/stores-overlay/index.njk @@ -1,4 +1,4 @@ {% extends '../../src/_includes/layout.njk' %} {% block html %} -
          + {% endblock %} diff --git a/samples/stores-overlay/index.ts b/samples/stores-overlay/index.ts index 1d21e288..838c5a7f 100644 --- a/samples/stores-overlay/index.ts +++ b/samples/stores-overlay/index.ts @@ -1,5 +1,7 @@ // [START woosmap_stores_overlay] -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + const center: woosmap.map.LatLngLiteral = { lat: 51.52, lng: -0.13 }; // [START woosmap_stores_overlay_style] const style: woosmap.map.Style = { @@ -28,24 +30,17 @@ function initMap(): void { // [END woosmap_stores_overlay_style] // [START woosmap_stores_overlay_add_map] - const map = new woosmap.map.Map( - document.getElementById("map") as HTMLElement, - { + const map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 4, center: center, - }, - ); + }); const storesOverlay = new woosmap.map.StoresOverlay(style); storesOverlay.setMap(map); // [END woosmap_stores_overlay_add_map] } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_overlay] export {}; diff --git a/samples/stores-overlay/stores-overlay.json b/samples/stores-overlay/stores-overlay.json index f5845d23..d0049b72 100644 --- a/samples/stores-overlay/stores-overlay.json +++ b/samples/stores-overlay/stores-overlay.json @@ -11,5 +11,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/stores-search-autocomplete-api/index.ts b/samples/stores-search-autocomplete-api/index.ts index 6c5b85eb..fc2cebca 100644 --- a/samples/stores-search-autocomplete-api/index.ts +++ b/samples/stores-search-autocomplete-api/index.ts @@ -123,17 +123,17 @@ function buildQueryString(params: object) { return queryStringParts.join("&"); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { diff --git a/samples/stores-search/index.njk b/samples/stores-search/index.njk index bcd8d340..981f631c 100644 --- a/samples/stores-search/index.njk +++ b/samples/stores-search/index.njk @@ -27,7 +27,7 @@ -
          + {% endblock %} diff --git a/samples/stores-search/index.ts b/samples/stores-search/index.ts index 9da0d077..0b7d9daa 100644 --- a/samples/stores-search/index.ts +++ b/samples/stores-search/index.ts @@ -1,6 +1,6 @@ // [START woosmap_stores_search] let map: woosmap.map.Map; -let activeLocation: woosmap.map.Marker | null = null; +let activeLocation: woosmap.map.marker.AdvancedMarkerElement | null = null; let storesOverlay: woosmap.map.StoresOverlay; const gestureMode: woosmap.map.GestureHandlingMode = "greedy"; let storesService: woosmap.map.StoresService; @@ -31,8 +31,6 @@ const storesStyle: woosmap.map.Style = { }; const mapOptions: woosmap.map.MapOptions = { - center: { lat: 51.50940214, lng: -0.133012 }, - zoom: 12, styles: [ { featureType: "poi.business", @@ -145,7 +143,9 @@ function handleGeocodeResults( localities: woosmap.map.localities.LocalitiesGeocodeResponse, ) { const location = localities.results[0]?.geometry?.location; - location && handleStoresSearch(location); + if (location) { + handleStoresSearch(location); + } } function handleStoresSearch(latlng: woosmap.map.LatLngLiteral) { @@ -202,15 +202,16 @@ function displayStoresAndLocation( } if (stores && latlng) { - activeLocation = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#5588FF", + borderColor: "#3D6FE0", + glyphColor: "#FFFFFF", + }); + + activeLocation = new woosmap.map.marker.AdvancedMarkerElement({ position: latlng, - icon: { - url: "https://images.woosmap.com/marker.png", - scaledSize: { - height: 50, - width: 32, - }, - }, + content: pin.element, }); const bounds = calculateLatLngBounds(stores); @@ -220,15 +221,17 @@ function displayStoresAndLocation( } } -function initMap() { - map = new window.woosmap.map.Map( - document.getElementById("map") as HTMLElement, - mapOptions, - ); +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions(mapOptions); + map.moveCamera({ center: { lat: 51.50940214, lng: -0.133012 }, zoom: 12 }); storesOverlay = new woosmap.map.StoresOverlay(storesStyle); storesOverlay.setMap(map); - map.data.setStyle((feature: woosmap.map.data.Feature) => { + map.data.setStyle((feature: woosmap.map.Data.Feature) => { const iconPint = feature.getProperty("highlighted") ? "https://images.woosmap.com/starbucks-marker-selected.svg" : "https://images.woosmap.com/starbucks-marker.svg"; @@ -236,7 +239,9 @@ function initMap() { }); map.addListener("click", (e) => { - e.latlng && handleGeocode(e.latlng); + if (e.latlng) { + handleGeocode(e.latlng); + } }); storesService = new woosmap.map.StoresService(); @@ -247,12 +252,7 @@ function handleError(error: woosmap.map.errors.APIError) { console.error("Error:", error); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_stores_search] export {}; diff --git a/samples/stores-search/stores-search.json b/samples/stores-search/stores-search.json index 6ff9cf5a..af7ff943 100644 --- a/samples/stores-search/stores-search.json +++ b/samples/stores-search/stores-search.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/transit-advanced/index.njk b/samples/transit-advanced/index.njk index 2ca15dc8..431e4b28 100644 --- a/samples/transit-advanced/index.njk +++ b/samples/transit-advanced/index.njk @@ -101,7 +101,7 @@
          -
          +
          Drag markers to update route
          diff --git a/samples/transit-advanced/index.ts b/samples/transit-advanced/index.ts index 4a503c77..6123dac6 100644 --- a/samples/transit-advanced/index.ts +++ b/samples/transit-advanced/index.ts @@ -2,7 +2,7 @@ let map: woosmap.map.Map; let transitService: woosmap.map.TransitService; let transitRequest: woosmap.map.transit.TransitRouteRequest; -let markersArray: woosmap.map.Marker[] = []; +let markersArray: woosmap.map.marker.AdvancedMarkerElement[] = []; let originContainer: HTMLElement; let destinationContainer: HTMLElement; let transitRenderer: woosmap.map.TransitRenderer; @@ -10,24 +10,15 @@ let transitRenderer: woosmap.map.TransitRenderer; function createMarker( position: woosmap.map.LatLngLiteral | woosmap.map.LatLng, label: string, - url: string, -): woosmap.map.Marker { - return new woosmap.map.Marker({ + background: string, +): woosmap.map.marker.AdvancedMarkerElement { + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ background, glyphText: label, glyphColor: "#FFFFFF" }); + return new woosmap.map.marker.AdvancedMarkerElement({ map, position, - draggable: true, - icon: { - url, - labelOrigin: new woosmap.map.Point(13, 15), - scaledSize: { - height: 38, - width: 26, - }, - }, - label: { - text: label, - color: "white", - }, + gmpDraggable: true, + content: pin.element, }); } @@ -40,26 +31,18 @@ function clearMarkers(): void { function displayTransitMarkers(): void { clearMarkers(); - const originMarker = createMarker( - transitRequest.origin, - "O", - "https://images.woosmap.com/marker-blue.svg", - ); + const originMarker = createMarker(transitRequest.origin, "O", "#3d5afe"); originMarker.addListener("dragend", () => { - transitRequest.origin = originMarker.getPosition(); - setLatLngToContainer(originContainer, originMarker.getPosition().toJSON()); + transitRequest.origin = originMarker.position!; + setLatLngToContainer(originContainer, originMarker.position!.toJSON()); calculateTransit(); }); - const destinationMarker = createMarker( - transitRequest.destination, - "D", - "https://images.woosmap.com/marker-red.svg", - ); + const destinationMarker = createMarker(transitRequest.destination, "D", "#f50057"); destinationMarker.addListener("dragend", () => { - transitRequest.destination = destinationMarker.getPosition(); + transitRequest.destination = destinationMarker.position!; setLatLngToContainer( destinationContainer, - destinationMarker.getPosition().toJSON(), + destinationMarker.position!.toJSON(), ); calculateTransit(); }); @@ -283,11 +266,7 @@ function updateTime(timeType: "departureTime" | "arrivalTime"): void { }); } -function registerAddButton( - selector: string, - element: HTMLElement, - loc: woosmap.map.LatLngLiteral[] | woosmap.map.LatLngLiteral, -): void { +function registerAddButton(selector: string, element: HTMLElement): void { const button = document.querySelector(selector) as HTMLElement; button.addEventListener("click", () => { if (button.classList.contains("addLocation__selected")) { @@ -383,20 +362,16 @@ function initUI(): void { updateTime("departureTime"); updateTime("arrivalTime"); updateTransitOptions(); - registerAddButton( - ".addLocation__destinations", - destinationContainer, - transitRequest.destination as woosmap.map.LatLngLiteral, - ); - registerAddButton( - ".addLocation__origins", - originContainer, - transitRequest.origin as woosmap.map.LatLngLiteral, - ); + registerAddButton(".addLocation__destinations", destinationContainer); + registerAddButton(".addLocation__origins", originContainer); } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 45.482604, lng: 9.16924 }, zoom: 11, }); @@ -410,12 +385,7 @@ function initMap(): void { calculateTransit(); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_transit_advanced] export {}; diff --git a/samples/transit-advanced/transit-advanced.json b/samples/transit-advanced/transit-advanced.json index 77c856e2..33408e0c 100644 --- a/samples/transit-advanced/transit-advanced.json +++ b/samples/transit-advanced/transit-advanced.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/transit-roadbook/index.njk b/samples/transit-roadbook/index.njk index e6c91bc7..89ac73d2 100644 --- a/samples/transit-roadbook/index.njk +++ b/samples/transit-roadbook/index.njk @@ -103,7 +103,7 @@
          -
          +
          Drag markers to update route
          diff --git a/samples/transit-roadbook/index.ts b/samples/transit-roadbook/index.ts index 09bd776a..c991167b 100644 --- a/samples/transit-roadbook/index.ts +++ b/samples/transit-roadbook/index.ts @@ -2,7 +2,7 @@ let map: woosmap.map.Map; let transitService: woosmap.map.TransitService; let transitRequest: woosmap.map.transit.TransitRouteRequest; -let markersArray: woosmap.map.Marker[] = []; +let markersArray: woosmap.map.marker.AdvancedMarkerElement[] = []; let originContainer: HTMLElement; let destinationContainer: HTMLElement; let transitRenderer: woosmap.map.TransitRenderer; @@ -10,24 +10,15 @@ let transitRenderer: woosmap.map.TransitRenderer; function createMarker( position: woosmap.map.LatLngLiteral | woosmap.map.LatLng, label: string, - url: string, -): woosmap.map.Marker { - return new woosmap.map.Marker({ + background: string, +): woosmap.map.marker.AdvancedMarkerElement { + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ background, glyphText: label, glyphColor: "#FFFFFF" }); + return new woosmap.map.marker.AdvancedMarkerElement({ map, position, - draggable: true, - icon: { - url, - labelOrigin: new woosmap.map.Point(13, 15), - scaledSize: { - height: 38, - width: 26, - }, - }, - label: { - text: label, - color: "white", - }, + gmpDraggable: true, + content: pin.element, }); } @@ -40,26 +31,18 @@ function clearMarkers(): void { function displayTransitMarkers(): void { clearMarkers(); - const originMarker = createMarker( - transitRequest.origin, - "O", - "https://images.woosmap.com/marker-blue.svg", - ); + const originMarker = createMarker(transitRequest.origin, "O", "#3d5afe"); originMarker.addListener("dragend", () => { - transitRequest.origin = originMarker.getPosition(); - setLatLngToContainer(originContainer, originMarker.getPosition().toJSON()); + transitRequest.origin = originMarker.position!; + setLatLngToContainer(originContainer, originMarker.position!.toJSON()); calculateTransit(); }); - const destinationMarker = createMarker( - transitRequest.destination, - "D", - "https://images.woosmap.com/marker-red.svg", - ); + const destinationMarker = createMarker(transitRequest.destination, "D", "#f50057"); destinationMarker.addListener("dragend", () => { - transitRequest.destination = destinationMarker.getPosition(); + transitRequest.destination = destinationMarker.position!; setLatLngToContainer( destinationContainer, - destinationMarker.getPosition().toJSON(), + destinationMarker.position!.toJSON(), ); calculateTransit(); }); @@ -166,12 +149,12 @@ function createRoutesTable(response: woosmap.map.transit.TransitRouteResponse) { } `; $stepContainer.appendChild($step); - leg.travel_mode === `transit` - ? $step.insertAdjacentHTML( - "afterend", - ' > ', - ) - : ""; + if (leg.travel_mode === `transit`) { + $step.insertAdjacentHTML( + "afterend", + ' > ', + ); + } return $stepContainer; }, ); @@ -411,11 +394,7 @@ function updateTime(timeType: "departureTime" | "arrivalTime"): void { }); } -function registerAddButton( - selector: string, - element: HTMLElement, - loc: woosmap.map.LatLngLiteral[] | woosmap.map.LatLngLiteral, -): void { +function registerAddButton(selector: string, element: HTMLElement): void { const button = document.querySelector(selector) as HTMLElement; button.addEventListener("click", () => { if (button.classList.contains("addLocation__selected")) { @@ -511,20 +490,16 @@ function initUI(): void { updateTime("departureTime"); updateTime("arrivalTime"); updateTransitOptions(); - registerAddButton( - ".addLocation__destinations", - destinationContainer, - transitRequest.destination as woosmap.map.LatLngLiteral, - ); - registerAddButton( - ".addLocation__origins", - originContainer, - transitRequest.origin as woosmap.map.LatLngLiteral, - ); + registerAddButton(".addLocation__destinations", destinationContainer); + registerAddButton(".addLocation__origins", originContainer); } -function initMap(): void { - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ center: { lat: 45.482604, lng: 9.16924 }, zoom: 11, }); @@ -538,12 +513,7 @@ function initMap(): void { calculateTransit(); } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_transit_roadbook] export {}; diff --git a/samples/transit-roadbook/transit-roadbook.json b/samples/transit-roadbook/transit-roadbook.json index bdfeff77..9041f41b 100644 --- a/samples/transit-roadbook/transit-roadbook.json +++ b/samples/transit-roadbook/transit-roadbook.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/samples/vector-map/index.njk b/samples/vector-map/index.njk index 8f3c1a0e..920525cf 100644 --- a/samples/vector-map/index.njk +++ b/samples/vector-map/index.njk @@ -9,6 +9,6 @@ -
          + {% endblock %} diff --git a/samples/vector-map/index.ts b/samples/vector-map/index.ts index 2d95ae74..b6fab30b 100644 --- a/samples/vector-map/index.ts +++ b/samples/vector-map/index.ts @@ -2,7 +2,9 @@ // Initialize and add the map let map: woosmap.map.Map; -function initMap(): void { +async function initMap(): Promise { + await woosmap.map.importLibrary("maps"); + // [START woosmap_vector_map_instantiate_map] // The location of London const position: woosmap.map.LatLngLiteral = { @@ -11,7 +13,8 @@ function initMap(): void { }; // The map, centered at London - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.moveCamera({ zoom: 17, center: position, }); @@ -29,12 +32,7 @@ function initMap(): void { // [END woosmap_vector_tilt] } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_vector_map] export {}; diff --git a/samples/vector-map/vector-map.json b/samples/vector-map/vector-map.json index 73e33010..ce136a25 100644 --- a/samples/vector-map/vector-map.json +++ b/samples/vector-map/vector-map.json @@ -10,5 +10,6 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "loaderShim": true } diff --git a/samples/vite.config.11ty.js b/samples/vite.config.11ty.js index 350ce457..c52cf826 100644 --- a/samples/vite.config.11ty.js +++ b/samples/vite.config.11ty.js @@ -20,6 +20,9 @@ export default defineConfig({ server: { hmr: process.env.CODESANDBOX_SSE ? 443 : undefined, }, + oxc: { + jsx: "automatic", + }, }); `; }, diff --git a/samples/w3w-autocomplete/index.njk b/samples/w3w-autocomplete/index.njk index cdfe2bee..b1345c6b 100644 --- a/samples/w3w-autocomplete/index.njk +++ b/samples/w3w-autocomplete/index.njk @@ -44,7 +44,7 @@
            -
            + {% endblock %} diff --git a/samples/w3w-autocomplete/index.ts b/samples/w3w-autocomplete/index.ts index da55b5b7..256b3ca5 100644 --- a/samples/w3w-autocomplete/index.ts +++ b/samples/w3w-autocomplete/index.ts @@ -13,10 +13,8 @@ let inputElement: HTMLInputElement; let detailsHTML: HTMLElement; let clearSearchBtn: HTMLButtonElement; let map: woosmap.map.Map; -let marker: woosmap.map.Marker; -let debouncedAutosuggestW3W: ( - ...args: any[] -) => Promise; +let marker: woosmap.map.marker.AdvancedMarkerElement; +let debouncedAutosuggestW3W: typeof autosuggestW3W; const API_KEY = "YOUR_API_KEY"; // Replace YOUR_API_KEY with your actual API key @@ -115,8 +113,7 @@ function panMap(addressDetail) { if (addressDetail.types[0] === "address") { zoom = 18; } - map.setZoom(zoom); - map.panTo(addressDetail.geometry.location); + map.moveCamera({ zoom, center: addressDetail.geometry.location }); } } @@ -124,15 +121,16 @@ function createAddressMarker(addressDetail) { if (marker) { marker.setMap(null); } - marker = new woosmap.map.Marker({ + const { PinElement } = woosmap.map.marker; + const pin = new PinElement({ + background: "#E00084", + borderColor: "#B3006A", + glyphColor: "#FFFFFF", + }); + + marker = new woosmap.map.marker.AdvancedMarkerElement({ position: addressDetail.geometry.location, - icon: { - url: "https://images.woosmap.com/marker-alt.png", - scaledSize: { - height: 59, - width: 37, - }, - }, + content: pin.element, }); marker.setMap(map); panMap(addressDetail); @@ -200,10 +198,10 @@ function displaySubBuildings(target: HTMLElement, subBuildings) { displaySection(autoSuggestResultsTitle); const addressList = document.createElement("ul"); - subBuildings.forEach((address, index) => { + subBuildings.forEach((address) => { const line = document.createElement("li"); line.className = "address"; - line.addEventListener("click", (event) => { + line.addEventListener("click", () => { getAddressDetails(line, address.public_id); }); line.innerHTML = `${address.description}`; @@ -234,10 +232,10 @@ function displayAddressList(addressDetails) { "what3words address invalid or no street address found within 200m of its location."; newAddressList.appendChild(line); } else { - addressDetails.forEach((address, index) => { + addressDetails.forEach((address) => { const line = document.createElement("li"); line.className = "address"; - line.addEventListener("click", (event) => { + line.addEventListener("click", () => { if (address.public_id) { getAddressDetails(line, address.public_id); } else { @@ -333,16 +331,15 @@ function displayW3wSuggestion() { // [END woosmap_w3w_autocomplete_displayW3wSuggestion] } -function initMap() { +async function initMap() { + await woosmap.map.importLibrary("maps"); + await woosmap.map.importLibrary("marker"); + // [START woosmap_w3w_autocomplete_initMap] - map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, { - center: { - lat: 48.8534, - lng: 2.3488, - }, + map = (document.getElementById("map") as woosmap.map.MapElement).innerMap; + map.setOptions({ disableDefaultUI: true, gestureHandling: "greedy", - zoom: 5, styles: [ { featureType: "poi", @@ -350,6 +347,13 @@ function initMap() { }, ], }); + map.moveCamera({ + center: { + lat: 48.8534, + lng: 2.3488, + }, + zoom: 5, + }); // [END woosmap_w3w_autocomplete_initMap] debouncedAutosuggestW3W = debouncePromise(autosuggestW3W, 0); initUI(); @@ -411,17 +415,17 @@ function initUI() { clearSearchBtn.addEventListener("click", resetUI); } -type DebouncePromiseFunction = ( +type DebouncePromiseFunction = ( ...args: Args ) => Promise; -function debouncePromise( +function debouncePromise( fn: (...args: Args) => Promise, delay: number, ): DebouncePromiseFunction { let timeoutId: ReturnType | null = null; let latestResolve: ((value: T | PromiseLike) => void) | null = null; - let latestReject: ((reason?: any) => void) | null = null; + let latestReject: ((reason?: unknown) => void) | null = null; return function (...args: Args): Promise { return new Promise((resolve, reject) => { @@ -447,12 +451,7 @@ function debouncePromise( }; } -declare global { - interface Window { - initMap: () => void; - } -} -window.initMap = initMap; +initMap(); // [END woosmap_w3w_autocomplete] export {}; diff --git a/samples/w3w-autocomplete/w3w-autocomplete.json b/samples/w3w-autocomplete/w3w-autocomplete.json index 7233aeba..15f5a5a1 100644 --- a/samples/w3w-autocomplete/w3w-autocomplete.json +++ b/samples/w3w-autocomplete/w3w-autocomplete.json @@ -10,5 +10,7 @@ "size": 1, "alias": "mode" }, - "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}" + "permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}", + "libraries": "marker", + "loaderShim": true } diff --git a/shared/scss/_default.scss b/shared/scss/_default.scss index 7279665b..aa3a6665 100644 --- a/shared/scss/_default.scss +++ b/shared/scss/_default.scss @@ -1,8 +1,12 @@ /* - * Always set the map height explicitly to define the size of the div element - * that contains the map. + * Always set the map height explicitly to define the size of the element + * that contains the map. `display: block` is required for /, + * which default to inline like any other custom element outside a flex/grid + * container (no-op for a plain
            ). */ #map { + display: block; + width: 100%; height: 100%; } diff --git a/src/_includes/layout.njk b/src/_includes/layout.njk index 3e8b25d8..d8203708 100644 --- a/src/_includes/layout.njk +++ b/src/_includes/layout.njk @@ -21,8 +21,40 @@ {% block html %}{% endblock %} {% block api %} - + {% else %} + + {% endif %} {% endblock %} diff --git a/src/engines/typescript/sample.js b/src/engines/typescript/sample.js index 14f5fe17..cffd70ca 100644 --- a/src/engines/typescript/sample.js +++ b/src/engines/typescript/sample.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-require-imports */ const ts = require("typescript"); const fs = require("fs"); const path = require("path"); diff --git a/src/transforms/your-api-key.js b/src/transforms/your-api-key.js index 2cca1f5f..23ba90d2 100644 --- a/src/transforms/your-api-key.js +++ b/src/transforms/your-api-key.js @@ -8,6 +8,10 @@ module.exports = function (content, outputPath) { /"YOUR_API_KEY"/g, "import.meta.env.VITE_WOOSMAP_PUBLIC_API_KEY!", ); + content = content.replace( + /"https:\/\/sdk\.woosmap\.com"/g, + "import.meta.env.VITE_WOOSMAP_SDK_HOST", + ); content = content.replace( /"YOUR_GOOGLE_API_KEY"/g, "import.meta.env.VITE_GOOGLE_API_KEY!",