Skip to content
This repository has been archived by the owner on Dec 20, 2024. It is now read-only.

Commit

Permalink
feat: use here maps js npm package
Browse files Browse the repository at this point in the history
  • Loading branch information
KhaledSakr committed Dec 13, 2024
1 parent 324b3d3 commit f3ee135
Show file tree
Hide file tree
Showing 16 changed files with 136 additions and 234 deletions.
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@here:registry=https://repo.platform.here.com/artifactory/api/npm/maps-api-for-javascript/
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
react-here-maps
==============

React Wrapper for the HERE Maps API for JavaScript (v3.0.12.4)
React Wrapper for the HERE Maps API for JavaScript (v3.1)

[![Version][npm-image]][npm-url] [![Gemnasium][gemnasium-image]][gemnasium-url] [![Travis][travis-ci-image]][travis-ci-url] [![Coveralls][coveralls-image]][coveralls-url]

Expand All @@ -22,7 +22,16 @@ The documentation provided in this README is specific to the platform. Note that
Dependencies
--------------

The module will automatically load the [HERE Maps API][here-maps-link] scripts and stylesheets for you. We follow this practice because the scripts themselves are split into multiple modules and we hope to conditionally load these scripts at some point in the future based on the features that the user of the module wishes to use.
The module is dependant on @here/maps-api-for-javascript packaged and hosted by HERE. To make sure it installs correctly in your environment, make sure you have the correct registry URL configured.

- Run this
```
npm config set @here:registry https://repo.platform.here.com/artifactory/api/npm/maps-api-for-javascript/
```
- Or, add this to your .npmrc
```
@here:registry=https://repo.platform.here.com/artifactory/api/npm/maps-api-for-javascript/
```

Quick Start
--------------
Expand Down
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,8 @@
"@impargo/eslint-config": "^1.4.0",
"@types/chai": "^4.0.1",
"@types/enzyme": "^3.10.8",
"@types/heremaps": "^3.1.5",
"@types/highlight.js": "^9.1.9",
"@types/jquery": "^3.2.6",
"@types/loadjs": "^4.0.0",
"@types/lodash": "^4.14.68",
"@types/mocha": "^2.2.41",
"@types/node": "^14.14.8",
Expand Down Expand Up @@ -112,7 +110,7 @@
"watchify": "^3.7.0"
},
"dependencies": {
"loadjs": "^4.2.0",
"@here/maps-api-for-javascript": "^1.61.1",
"lodash": "^4.15.0"
},
"peerDependencies": {
Expand Down
137 changes: 70 additions & 67 deletions src/HEREMap.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import '@here/maps-api-for-javascript/bin/mapsjs.bundle.harp.js'

import { debounce, uniqueId } from 'lodash'
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'

import { HEREMapContext } from './context'
import type { DefaultLayers } from './types'
import { useRasterLayers } from './useRasterLayers'
import { useVectorLayers } from './useVectorLayers'
import { loadScripts } from './utils/cache'
import getPlatform from './utils/get-platform'
import { Language } from './utils/languages'

Expand All @@ -18,6 +20,9 @@ export interface HEREMapProps extends H.Map.Options {
hidpi?: boolean,
interactive?: boolean,
lg?: Language,
/**
* @deprecated no longer supported. HERE Maps JS is now bundled with this package.
*/
secure?: boolean,
routes?: object[],
truckRestrictions?: boolean,
Expand All @@ -36,6 +41,9 @@ export interface HEREMapProps extends H.Map.Options {
* If you want to change it, you have to re-mount the map component.
*/
useVectorTiles?: boolean,
/**
* @deprecated no longer supported. HERE Maps JS is now bundled with this package so there can longer be script loading errors.
*/
onScriptLoadError?: (failedScripts: string[]) => void,

useLegacyTruckLayer?: boolean,
Expand Down Expand Up @@ -66,8 +74,6 @@ export interface HEREMapRef {

export const HEREMap = forwardRef<HEREMapRef, HEREMapProps>(({
children,
secure,
onScriptLoadError,
center,
hidpi,
interactive = true,
Expand Down Expand Up @@ -95,7 +101,7 @@ export const HEREMap = forwardRef<HEREMapRef, HEREMapProps>(({

const markersGroupsRef = useRef<Record<string, H.map.Group>>({})

const defaultLayersRef = useRef<H.service.DefaultLayers>(null)
const defaultLayersRef = useRef<DefaultLayers>(null)

useVectorLayers({
congestion,
Expand All @@ -122,6 +128,7 @@ export const HEREMap = forwardRef<HEREMapRef, HEREMapProps>(({
useLegacyTruckLayer,
useSatellite,
useVectorTiles,
hidpi,
})

const unmountedRef = useRef(false)
Expand Down Expand Up @@ -197,73 +204,69 @@ export const HEREMap = forwardRef<HEREMapRef, HEREMapProps>(({
}, [map])

Check warning on line 204 in src/HEREMap.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useImperativeHandle has missing dependencies: 'addToMarkerGroup', 'animateCenter', 'animateZoom', 'removeFromMarkerGroup', 'screenToGeo', 'zoomOnMarkers', and 'zoomOnMarkersSet'. Either include them or remove the dependency array

useEffect(() => {
loadScripts(secure, !useVectorTiles).then(() => {
if (unmountedRef.current) {
return
}
if (unmountedRef.current) {
return
}

// get the platform to base the maps on
const platform = getPlatform({
apikey: apiKey,
useHTTPS: secure === true,
})
defaultLayersRef.current = platform.createDefaultLayers({
lg,
ppi: hidpi ? 320 : 72,
})

const hereMapEl = document.querySelector(`#map-container-${uniqueIdRef.current}`)
const baseLayer = useVectorTiles
? defaultLayersRef.current.vector.normal.map
: defaultLayersRef.current.raster.normal.map
const newMap = new H.Map(
hereMapEl,
baseLayer,
{
center,
// @ts-ignore
engineType: useVectorTiles ? undefined : H.map.render.RenderEngine.EngineType.P2D,
pixelRatio: hidpi ? 2 : 1,
zoom,
},
)

const routesProvider = new H.map.provider.LocalObjectProvider()
const routesLayer = new H.map.layer.ObjectLayer(routesProvider)
newMap.addLayer(routesLayer)

let ui: H.ui.UI

// make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom
const behavior = interactive ? new H.mapevents.Behavior(new H.mapevents.MapEvents(newMap)) : undefined

if (behavior) {
if (!useVectorLayers) {
// @ts-ignore
behavior.disable(H.mapevents.Behavior.Feature.FRACTIONAL_ZOOM)
}
// get the platform to base the maps on
const platform = getPlatform({
apikey: apiKey,
})

const engineType = useVectorTiles ? H.Map.EngineType.HARP : H.Map.EngineType.P2D

defaultLayersRef.current = platform.createDefaultLayers({
lg,
engineType,
}) as DefaultLayers

const hereMapEl = document.querySelector(`#map-container-${uniqueIdRef.current}`) as HTMLElement
const baseLayer = useVectorTiles
? defaultLayersRef.current.vector.normal.map
: defaultLayersRef.current.raster.normal.map
const newMap = new H.Map(
hereMapEl,
baseLayer,
{
center,
engineType,
pixelRatio: hidpi ? 2 : 1,
zoom,
},
)

// create the default UI for the map
ui = H.ui.UI.createDefault(newMap, defaultLayersRef.current, language)
if (disableMapSettings) {
ui.removeControl('mapsettings')
}
const routesProvider = new H.map.provider.LocalObjectProvider()
const routesLayer = new H.map.layer.ObjectLayer(routesProvider)
newMap.addLayer(routesLayer)

let ui: H.ui.UI

// make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom
const behavior = interactive ? new H.mapevents.Behavior(new H.mapevents.MapEvents(newMap)) : undefined

if (behavior) {
behavior.disable(H.mapevents.Behavior.Feature.FRACTIONAL_ZOOM)

// create the default UI for the map
ui = H.ui.UI.createDefault(newMap, defaultLayersRef.current, language)
if (disableMapSettings) {
ui.removeControl('mapsettings')
}
}

setMap(newMap)
setRoutesGroup(routesProvider.getRootGroup())

onMapAvailable({
behavior,
map: newMap,
markersGroups: markersGroupsRef.current,
routesGroup: routesProvider.getRootGroup(),
trafficLayer,
ui,
})
}).catch(onScriptLoadError)
setMap(newMap)
setRoutesGroup(routesProvider.getRootGroup())

onMapAvailable({
behavior,
map: newMap,
markersGroups: markersGroupsRef.current,
routesGroup: routesProvider.getRootGroup(),
trafficLayer,
ui,
})

return () => {
unmountedRef.current = true
Expand Down
9 changes: 4 additions & 5 deletions src/Marker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import getMarkerIcon from './utils/get-marker-icon'

// declare an interface containing the required and potential
// props that can be passed to the HEREMap Marker componengetMartkerIdt
export interface MarkerProps extends H.map.Marker.Options, EventHandlers {
export interface MarkerProps extends Omit<H.map.Marker.Options, 'data'>, EventHandlers {
lat: number,
lng: number,
/**
* Either an image URL or an SVG markup.
*/
bitmap?: string,
data?: any,
data?: unknown,
draggable?: boolean,
/**
* @deprecated use bitmap instead. Passing children in this way has performance
Expand Down Expand Up @@ -78,16 +78,16 @@ export const Marker: FC<MarkerProps> = ({
let newMarker = null
if (React.Children.count(children) > 0) {
const icon = renderChildren()
newMarker = new H.map.DomMarker({ lat, lng }, { icon })
newMarker = new H.map.DomMarker({ lat, lng }, { icon, data: null })
} else if (bitmap) {
// if we have an image url or an svg markup and no react children, create a
// regular icon instance
const icon = getMarkerIcon(bitmap, anchor)
// then create a normal marker instance and attach it to the map
newMarker = new H.map.Marker({ lat, lng }, {
icon,
// @ts-ignore
volatility: draggable,
data: null,
...options,
})
} else {
Expand Down Expand Up @@ -121,7 +121,6 @@ export const Marker: FC<MarkerProps> = ({
useEffect(() => {
if (marker) {
marker.draggable = draggable
// @ts-ignore
marker.setVolatility(draggable)
}
}, [marker, draggable])
Expand Down
1 change: 0 additions & 1 deletion src/Route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export const Route: FC<RoutesProps> = ({

useEffect(() => {
if (polyline && typeof draggable === 'boolean') {
// @ts-ignore
polyline.draggable = draggable
}
}, [polyline, draggable])
Expand Down
26 changes: 26 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export interface DefaultLayers {
raster: {
normal: {
map: H.map.layer.BaseTileLayer,
base: H.map.layer.BaseTileLayer,
trafficincidents: H.map.layer.TileLayer,
},
satellite: {
map: H.map.layer.BaseTileLayer,
},
},
vector: {
normal: {
map: H.map.layer.BaseTileLayer,
trafficincidents: H.map.layer.TileLayer,
traffic: H.map.layer.TileLayer,
truck: H.map.layer.TileLayer,
},
},
hybrid: {
logistics: {
raster: H.map.layer.BaseTileLayer,
vector: H.map.layer.BaseTileLayer,
},
},
}
11 changes: 6 additions & 5 deletions src/useRasterLayers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useMemo } from 'react'

import type { DefaultLayers } from './types'
import { Language } from './utils/languages'

export interface UseRasterLayersProps {
Expand All @@ -9,7 +10,7 @@ export interface UseRasterLayersProps {
incidentsLayer?: boolean,
useSatellite?: boolean,
congestion?: boolean,
defaultLayers?: H.service.DefaultLayers,
defaultLayers?: DefaultLayers,
apiKey: string,
hidpi?: boolean,
useVectorTiles: boolean,
Expand All @@ -31,7 +32,7 @@ const getLayers = (
useLegacyTrafficLayer?: boolean,
) => {

Check warning on line 33 in src/useRasterLayers.ts

View workflow job for this annotation

GitHub Actions / lint

Refactor this function to reduce its Cognitive Complexity from 21 to the 15 allowed
const lang = locale ?? 'en'
const ppi = hidpi ? 400 : 100
const ppi = hidpi ? '&ppi=400' : ''
const format = 'png8'

const getTruckLayerProvider = (enableCongestion: boolean): H.map.provider.ImageTileProvider.Options => {
Expand All @@ -43,22 +44,22 @@ const getLayers = (
? 'vehicle_restrictions:active_and_inactive,environmental_zones:all,congestion_zones:all'
: 'vehicle_restrictions:active_and_inactive'
const style = 'logistics.day'
return `https://maps.hereapi.com/v3/blank/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}&features=${features}&lang=${lang}&ppi=${ppi}&style=${style}`
return `https://maps.hereapi.com/v3/blank/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}&features=${features}&lang=${lang}&style=${style}${ppi}`
},
}
}
const getTrafficOverlayProvider = (): H.map.provider.ImageTileProvider.Options => {
return {
getURL (col, row, level) {
return `https://traffic.maps.hereapi.com/v3/flow/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}&ppi=${ppi}`
return `https://traffic.maps.hereapi.com/v3/flow/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}${ppi}`
},
}
}
const getTrafficBaseProvider = (): H.map.provider.ImageTileProvider.Options => {
return {
getURL (col, row, level) {
const style = 'lite.day'
return `https://maps.hereapi.com/v3/base/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}&lang=${lang}&ppi=${ppi}&style=${style}`
return `https://maps.hereapi.com/v3/base/mc/${level}/${col}/${row}/${format}?apiKey=${apiKey}&lang=${lang}&style=${style}${ppi}`
},
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/useVectorLayers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { useEffect } from 'react'

import { DefaultLayers } from './types'

export interface UseVectorLayersProps {
map?: H.Map,
truckRestrictions?: boolean,
trafficLayer?: boolean,
incidentsLayer?: boolean,
useSatellite?: boolean,
congestion?: boolean,
defaultLayers?: H.service.DefaultLayers,
defaultLayers?: DefaultLayers,
useVectorTiles: boolean,
}

Expand All @@ -24,7 +26,6 @@ export const useVectorLayers = ({
useEffect(() => {
if (map && defaultLayers && useVectorTiles) {
if (truckRestrictions) {
// @ts-ignore
map.setBaseLayer(defaultLayers.vector.normal.truck)
} else {
map.setBaseLayer(useSatellite
Expand Down
Loading

0 comments on commit f3ee135

Please sign in to comment.