### Initialize Platform, Map, and UI Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Initializes the HERE Maps Platform, renders a map centered over Berlin, and adds default interactivity and UI controls. Remember to replace `window.apikey` with your actual API key. ```javascript // Step 1 — authenticate var platform = new H.service.Platform({ apikey: window.apikey }); var defaultLayers = platform.createDefaultLayers(); // Step 2 — render map centered over Berlin var map = new H.Map( document.getElementById('map'), defaultLayers.vector.normal.map, { center: { lat: 52.5159, lng: 13.3777 }, zoom: 14, pixelRatio: window.devicePixelRatio || 1, } ); // Responsive resize window.addEventListener('resize', () => map.getViewPort().resize()); // Step 3 — interactivity and default UI var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)); var ui = H.ui.UI.createDefault(map, defaultLayers); // Navigate programmatically map.setCenter({ lat: 48.8566, lng: 2.3522 }); // Paris map.setZoom(12); ``` -------------------------------- ### Platform and Map Initialisation Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Initialise the HERE Maps Platform with your API key, create a map instance, and add interactivity and default UI controls. ```APIDOC ## Platform and Map Initialisation — H.service.Platform / H.Map ### Description The entry point for every HERE Maps application. `H.service.Platform` authenticates requests, while `H.Map` renders the map inside a DOM container. `H.mapevents.Behavior` adds mouse/touch interactions and `H.ui.UI.createDefault` adds zoom controls, scale bar, and settings UI. ### Code Example ```javascript // Step 1 — authenticate var platform = new H.service.Platform({ apikey: window.apikey }); var defaultLayers = platform.createDefaultLayers(); // Step 2 — render map centered over Berlin var map = new H.Map( document.getElementById('map'), defaultLayers.vector.normal.map, { center: { lat: 52.5159, lng: 13.3777 }, zoom: 14, pixelRatio: window.devicePixelRatio || 1, } ); // Responsive resize window.addEventListener('resize', () => map.getViewPort().resize()); // Step 3 — interactivity and default UI var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)); var ui = H.ui.UI.createDefault(map, defaultLayers); // Navigate programmatically map.setCenter({ lat: 48.8566, lng: 2.3522 }); // Paris map.setZoom(12); ``` ``` -------------------------------- ### Map Capture / Screenshot Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Render the current map viewport (and optionally its UI elements) to an HTML5 `` element asynchronously using the `map.capture` method. ```APIDOC ## Map Capture / Screenshot — `map.capture` ### Description Render the current map viewport (and optionally its UI elements) to an HTML5 `` element asynchronously. ### Usage ```js function captureMap(map, ui, resultContainer) { // Arguments: callback, [ui components], x, y, width, height // Omit x/y/width/height to capture the entire viewport map.capture( function (canvas) { if (canvas) { resultContainer.innerHTML = ''; resultContainer.appendChild(canvas); } else { resultContainer.textContent = 'Capture not supported in this mode'; } }, [ui], // include UI (scale bar, zoom controls, etc.) 50, 50, // top-left origin within viewport 500, 200 // width and height of capture area ); } ``` ``` -------------------------------- ### Adding Markers Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Place point markers on the map. Use `H.map.Marker` with `H.map.Icon` for custom appearances. Markers can be grouped with `H.map.Group` to simplify event handling and bounding-box calculations. ```APIDOC ## Adding Markers — H.map.Marker / H.map.Icon ### Description Place point markers on the map. Use `H.map.Icon` (or `H.map.DomIcon`) for custom appearances. Markers can be grouped with `H.map.Group` to simplify event handling and bounding-box calculations. ### Code Example ```javascript // Simple default marker var marker = new H.map.Marker({ lat: 48.8567, lng: 2.3508 }); map.addObject(marker); // Custom SVG icon marker var svgMarkup = '' + '' + 'C'; var icon = new H.map.Icon(svgMarkup.replace('${FILL}', 'blue').replace('${STROKE}', 'red')); var iconMarker = new H.map.Marker({ lat: 41.8625, lng: -87.6166 }, { icon: icon }); map.addObject(iconMarker); // Group with tap event — centres map and opens bubble on click var group = new H.map.Group(); group.addEventListener('tap', function (evt) { map.setCenter(evt.target.getGeometry()); var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), { content: evt.target.getData(), }); ui.addBubble(bubble); }, false); var m = new H.map.Marker({ lat: 53.439, lng: -2.221 }); m.setData('Manchester City
Capacity: 55,097'); group.addObject(m); map.addObject(group); ``` ``` -------------------------------- ### Synchronising Two Maps Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Mirror the camera state from one map instance to another in real time using the `mapviewchange` event and `ViewModel.setLookAtData`, via `map.addEventListener('mapviewchange', ...)`. ```APIDOC ## Synchronising Two Maps — `map.addEventListener('mapviewchange', ...)` ### Description Mirror the camera state from one map instance to another in real time using the `mapviewchange` event and `ViewModel.setLookAtData`. ### Usage ```js function synchronizeMaps(primaryMap, mirrorMap) { var vm1 = primaryMap.getViewModel(); var vm2 = mirrorMap.getViewModel(); primaryMap.addEventListener('mapviewchange', function () { // Copy all geo-state (center, zoom, tilt, heading) from primary to mirror vm2.setLookAtData(vm1.getLookAtData()); }); } ``` ``` -------------------------------- ### Synchronize Two Map Views Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Mirrors the camera state (center, zoom, tilt, heading) from one map instance to another in real time using the `mapviewchange` event and `ViewModel.setLookAtData`. ```javascript function synchronizeMaps(primaryMap, mirrorMap) { var vm1 = primaryMap.getViewModel(); var vm2 = mirrorMap.getViewModel(); primaryMap.addEventListener('mapviewchange', function () { // Copy all geo-state (center, zoom, tilt, heading) from primary to mirror vm2.setLookAtData(vm1.getLookAtData()); }); } ``` -------------------------------- ### Add Default and Custom Icon Markers to Map Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Demonstrates adding a default marker and a custom marker with an SVG icon. Markers can be grouped for simplified event handling and bounding box calculations. ```javascript // Simple default marker var marker = new H.map.Marker({ lat: 48.8567, lng: 2.3508 }); map.addObject(marker); // Custom SVG icon marker var svgMarkup = '' + '' + 'C'; var icon = new H.map.Icon(svgMarkup.replace('${FILL}', 'blue').replace('${STROKE}', 'red')); var iconMarker = new H.map.Marker({ lat: 41.8625, lng: -87.6166 }, { icon: icon }); map.addObject(iconMarker); // Group with tap event — centres map and opens bubble on click var group = new H.map.Group(); group.addEventListener('tap', function (evt) { map.setCenter(evt.target.getGeometry()); var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), { content: evt.target.getData(), }); ui.addBubble(bubble); }, false); var m = new H.map.Marker({ lat: 53.439, lng: -2.221 }); m.setData('Manchester City
Capacity: 55,097'); group.addObject(m); map.addObject(group); ``` -------------------------------- ### Discover Landmarks and Places Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Search for points of interest by name and location using `platform.getSearchService().discover`. Centers the map on the first result and logs its details. ```javascript function landmarkGeocode(platform) { platform.getSearchService().discover( { q: 'Eiffel Tower', at: '48.8566,2.3522', limit: 1 }, function onSuccess(result) { var place = result.items[0]; map.addObject(new H.map.Marker(place.position)); map.setCenter(place.position); map.setZoom(16); console.log(place.title, place.address.label); }, function onError(err) { alert(err); } ); } ``` -------------------------------- ### Apply Custom Map Style (Harp) Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Applies a custom vector tile style from a JSON file, replacing the default base map. Requires a HERE API Key. ```javascript var platform = new H.service.Platform({ apikey: window.apikey }); // Load a style JSON exported from https://platform.here.com/style-editor var style = new H.map.render.harp.Style('https://example.com/styles/night.json'); // Create a vector layer using the style var vectorLayer = platform.getOMVService().createLayer(style); var map = new H.Map( document.getElementById('map'), vectorLayer, // pass the styled layer directly { center: { lat: 52.5148, lng: 13.3984 }, zoom: 13, pixelRatio: window.devicePixelRatio || 1, } ); ``` -------------------------------- ### Open and Manage InfoBubble Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Displays an information bubble at a specified position with provided HTML content. Reuses a single bubble instance for efficiency. ```javascript var bubble; function openBubble(position, htmlContent) { if (!bubble) { bubble = new H.ui.InfoBubble(position, { content: htmlContent }); ui.addBubble(bubble); } else { bubble.setPosition(position); bubble.setContent(htmlContent); bubble.open(); } } // Triggered on marker tap: marker.addEventListener('tap', function (evt) { openBubble( evt.target.getGeometry(), 'Eiffel Tower
Paris, France' ); }); ``` -------------------------------- ### Add Custom Tile Overlay Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Overlays a custom TMS tile set on the map within specified zoom levels and opacity. Requires a function to provide tile URLs. ```javascript function addTileOverlay(map) { var tileProvider = new H.map.provider.ImageTileProvider({ min: 12, max: 15, opacity: 0.5, getURL: function (column, row, zoom) { // Return URL for each tile; null/blank for out-of-bounds tiles return 'https://mytileserver.example.com/' + zoom + '/' + row + '/' + column + '.png'; }, }); // Provide attribution tileProvider.getCopyrights = function () { return [{ label: 'My Map Tiles', alt: 'Custom tile layer' }]; }; map.addLayer(new H.map.layer.TileLayer(tileProvider, { opacity: 0.5 })); } ``` -------------------------------- ### Calculate Public Transit Route with HERE Maps API Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Calculates a public-transport route between two specified stops. Requires the platform object to be initialized. ```javascript function calculateTransitRoute(platform) { platform.getPublicTransitService().getRoutes( { origin: '52.5208,13.4093', // Fernsehturm, Berlin destination: '52.5034,13.3280', // Kurfürstendamm return: 'polyline,actions,travelSummary', }, function onSuccess(result) { result.routes[0].sections.forEach(function (section) { map.addObject(new H.map.Polyline( H.geo.LineString.fromFlexiblePolyline(section.polyline), { style: { lineWidth: 4, strokeColor: 'rgba(0, 128, 255, 0.7)' } } )); }); }, function onError() { alert("Transit routing failed"); } ); } ``` -------------------------------- ### Custom Tile Overlay Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Overlay a custom TMS (Tile Map Service) tile set on top of the base map at configurable zoom levels and opacity using H.map.provider.ImageTileProvider and H.map.layer.TileLayer. ```APIDOC ## Custom Tile Overlay — `H.map.provider.ImageTileProvider` / `H.map.layer.TileLayer` ### Description Overlay a custom TMS (Tile Map Service) tile set on top of the base map at configurable zoom levels and opacity. ### Usage ```js function addTileOverlay(map) { var tileProvider = new H.map.provider.ImageTileProvider({ min: 12, max: 15, opacity: 0.5, getURL: function (column, row, zoom) { // Return URL for each tile; null/blank for out-of-bounds tiles return 'https://mytileserver.example.com/' + zoom + '/' + row + '/' + column + '.png'; }, }); // Provide attribution tileProvider.getCopyrights = function () { return [{ label: 'My Map Tiles', alt: 'Custom tile layer' }]; }; map.addLayer(new H.map.layer.TileLayer(tileProvider, { opacity: 0.5 })); } ``` ``` -------------------------------- ### Landmark / Place Discovery — `platform.getSearchService().discover` Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Searches for landmarks and points of interest by name, with an optional proximity bias. It can return details about the found places, including their position, title, and address. ```APIDOC ## Landmark / Place Discovery — `platform.getSearchService().discover` ### Description Search for places and points of interest by name, with optional proximity bias. ### Usage ```js function landmarkGeocode(platform) { platform.getSearchService().discover( { q: 'Eiffel Tower', at: '48.8566,2.3522', limit: 1 }, function onSuccess(result) { var place = result.items[0]; map.addObject(new H.map.Marker(place.position)); map.setCenter(place.position); map.setZoom(16); console.log(place.title, place.address.label); }, function onError(err) { alert(err); } ); } ``` ``` -------------------------------- ### Programmatic Map Panning Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Drive continuous map movement via `viewport.interaction()` inside an animation loop, useful for auto-scrolling or animated tours, using `map.getViewPort().interaction`. ```APIDOC ## Programmatic Map Panning — `map.getViewPort().interaction` ### Description Drive continuous map movement via `viewport.interaction()` inside an animation loop, useful for auto-scrolling or animated tours. ### Usage ```js function panTheMap(map) { var viewPort = map.getViewPort(); var x = 100, y = 100, incX = 1, incY = 2; viewPort.startInteraction(H.map.render.RenderEngine.InteractionModifiers.COORD, 0, 0); setInterval(function () { x += incX; if (Math.abs(x) > 100) incX = -incX; y += incY; if (Math.abs(y) > 100) incY = -incY; viewPort.interaction(x, y); }, 15); } ``` ``` -------------------------------- ### Create SVG Graphic Markers with H.map.Icon Source: https://github.com/heremaps/maps-api-for-javascript-examples/blob/master/map-with-svg-graphic-markers/demo.html Use the H.map.Icon class to create SVG graphic images for markers. The icon is then added as a parameter when creating an H.map.Marker. ```javascript SVG Graphics images are created using the H.map.Icon class. The icon is added as a parameter when creating an H.map.Marker. ``` -------------------------------- ### Setting Map View Bounds Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Fit the visible viewport to a geographic bounding box using `H.geo.Rect` and `map.getViewModel().setLookAtData`. Useful when you want to display a specific region regardless of screen size. ```APIDOC ## Setting Map View Bounds — H.geo.Rect / map.getViewModel().setLookAtData ### Description Fit the visible viewport to a geographic bounding box using `H.geo.Rect` and `setLookAtData`. Useful when you want to display a specific region regardless of screen size. ### Code Example ```javascript // Display the area around Boston (top-left lat/lng, bottom-right lat/lng) var bbox = new H.geo.Rect(42.3736, -71.0751, 42.3472, -71.0408); map.getViewModel().setLookAtData({ bounds: bbox }); // Alternatively, zoom to fit a group of objects var group = new H.map.Group(); group.addObjects([ new H.map.Marker({ lat: 43.7, lng: -79.4 }), // Toronto new H.map.Marker({ lat: 42.35805, lng: -71.0636 }), // Boston new H.map.Marker({ lat: 38.8951, lng: -77.0366 }), // Washington ]); map.addObject(group); map.getViewModel().setLookAtData({ bounds: group.getBoundingBox() }); ``` ``` -------------------------------- ### Restrict Map Movement to a Bounding Box Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Implement map movement restrictions by listening to the 'sync' event on the view model. This ensures the map center stays within a defined bounding box. ```javascript function restrictMap(map) { var bounds = new H.geo.Rect(37.829, -122.426, 37.824, -122.420); map.getViewModel().addEventListener('sync', function () { var center = map.getCenter(); if (!bounds.containsPoint(center)) { center.lat = Math.min(Math.max(center.lat, bounds.getBottom()), bounds.getTop()); center.lng = Math.min(Math.max(center.lng, bounds.getLeft()), bounds.getRight()); map.setCenter(center); } }); } ``` -------------------------------- ### Programmatic Map Panning Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Drives continuous map movement using `viewport.interaction()` within an animation loop. Useful for auto-scrolling or animated tours. ```javascript function panTheMap(map) { var viewPort = map.getViewPort(); var x = 100, y = 100, incX = 1, incY = 2; viewPort.startInteraction(H.map.render.RenderEngine.InteractionModifiers.COORD, 0, 0); setInterval(function () { x += incX; if (Math.abs(x) > 100) incX = -incX; y += incY; if (Math.abs(y) > 100) incY = -incY; viewPort.interaction(x, y); }, 15); } ``` -------------------------------- ### Add Draggable Marker with Map Behavior Control Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Enables drag-and-drop repositioning for a marker. Requires map and behavior objects. Disables map panning during drag. ```javascript function addDraggableMarker(map, behavior) { var marker = new H.map.Marker( { lat: 42.35805, lng: -71.0636 }, { volatility: true } // enables smooth dragging ); marker.draggable = true; map.addObject(marker); map.addEventListener('dragstart', function (ev) { if (ev.target instanceof H.map.Marker) { var pos = map.geoToScreen(ev.target.getGeometry()); ev.target.offset = new H.math.Point( ev.currentPointer.viewportX - pos.x, ev.currentPointer.viewportY - pos.y ); behavior.disable(); // prevent map pan while dragging } }, false); map.addEventListener('drag', function (ev) { if (ev.target instanceof H.map.Marker) { ev.target.setGeometry( map.screenToGeo( ev.currentPointer.viewportX - ev.target.offset.x, ev.currentPointer.viewportY - ev.target.offset.y ) ); } }, false); map.addEventListener('dragend', function (ev) { if (ev.target instanceof H.map.Marker) behavior.enable(); }, false); } addDraggableMarker(map, behavior); ``` -------------------------------- ### Create 3D Extruded Objects Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Extrudes circles and polygons into 3D objects by setting the `extrusion` property. Requires a tilted map view. ```javascript // Set a tilted 3D view map.getViewModel().setLookAtData({ tilt: 38, heading: 245 }); // Extruded circle (column / cylinder) var column = new H.map.Circle( { lat: 48.8726, lng: 2.3357 }, 2, // radius in metres { extrusion: 40, style: { fillColor: '#0297A0', strokeColor: 'none' } } ); // Extruded polygon (building) var building = new H.map.Polygon( new H.geo.Polygon( new H.geo.LineString([48.8727, 2.3357, 0, 48.8730, 2.3362, 0, 48.8732, 2.3353, 0]) ), { extrusion: 90, style: { strokeColor: 'none' } } ); map.addObjects([column, building]); ``` -------------------------------- ### Public Transit Route Calculation Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Calculates a public-transport route between two stops, returning polyline geometry and travel summary. ```APIDOC ## Public Transit Route — `platform.getPublicTransitService().getRoutes` ### Description Calculate a public-transport route between two stops. ### Method Signature `platform.getPublicTransitService().getRoutes(options, onSuccess, onError)` ### Parameters #### `options` (Object) - `origin` (string) - The starting stop for the route (latitude,longitude). - `destination` (string) - The ending stop for the route (latitude,longitude). - `return` (string) - Specifies the data to be returned (e.g., 'polyline,actions,travelSummary'). #### `onSuccess` (Function) Callback function executed when the route calculation is successful. #### `onError` (Function) Callback function executed when the route calculation fails. ### Request Example ```js platform.getPublicTransitService().getRoutes( { origin: '52.5208,13.4093', // Fernsehturm, Berlin destination: '52.5034,13.3280', // Kurfürstendamm return: 'polyline,actions,travelSummary' }, onSuccess, onError ); ``` ### Response Example (onSuccess) ```js { "routes": [ { "sections": [ { "polyline": "...", // Flexible polyline encoded geometry "travelSummary": { "length": 5000, // Distance in meters "duration": 600 // Duration in seconds }, "actions": [...] // Public transit actions } ] } ] } ``` ``` -------------------------------- ### Add DOM Marker with Custom Styling and Events Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Embeds a real HTML element as a marker on the map, enabling native DOM events and CSS transitions. Requires a map instance. ```javascript function addDomMarker(map) { var outer = document.createElement('div'); var inner = document.createElement('div'); Object.assign(inner.style, { color: 'red', backgroundColor: 'blue', border: '2px solid black', font: 'normal 12px arial', width: '20px', height: '20px', marginTop: '-10px', marginLeft: '-10px', }); inner.innerHTML = 'C'; outer.appendChild(inner); var domIcon = new H.map.DomIcon(outer, { onAttach: function (clonedEl) { clonedEl.addEventListener('mouseover', function (e) { e.target.style.opacity = 0.6; }); clonedEl.addEventListener('mouseout', function (e) { e.target.style.opacity = 1; }); }, onDetach: function (clonedEl) { clonedEl.removeEventListener('mouseover', function (e) { e.target.style.opacity = 0.6; }); clonedEl.removeEventListener('mouseout', function (e) { e.target.style.opacity = 1; }); }, }); map.addObject(new H.map.DomMarker({ lat: 41.8625, lng: -87.6166 }, { icon: domIcon })); } ``` -------------------------------- ### Restricting Map Movement — `map.getViewModel().addEventListener('sync', ...)` Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Clamps the map center to a specified bounding box on every view change, preventing users from panning outside a permitted region. This is achieved by listening to the 'sync' event on the map's view model. ```APIDOC ## Restricting Map Movement — `map.getViewModel().addEventListener('sync', ...)` ### Description Clamp the map center to a bounding box on every view change to prevent users from panning outside a permitted region. ### Usage ```js function restrictMap(map) { var bounds = new H.geo.Rect(37.829, -122.426, 37.824, -122.420); map.getViewModel().addEventListener('sync', function () { var center = map.getCenter(); if (!bounds.containsPoint(center)) { center.lat = Math.min(Math.max(center.lat, bounds.getBottom()), bounds.getTop()); center.lng = Math.min(Math.max(center.lng, bounds.getLeft()), bounds.getRight()); map.setCenter(center); } }); } ``` ``` -------------------------------- ### Custom Map Style (Harp) Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Apply a custom vector tile style exported from the HERE Style Editor. This replaces the default base map layer with the styled OMV layer using H.map.render.harp.Style and platform.getOMVService().createLayer. ```APIDOC ## Custom Map Style (Harp) — `H.map.render.harp.Style` / `platform.getOMVService().createLayer` ### Description Apply a custom vector tile style exported from the HERE Style Editor. This replaces the default base map layer with the styled OMV layer. ### Usage ```js var platform = new H.service.Platform({ apikey: window.apikey }); // Load a style JSON exported from https://platform.here.com/style-editor var style = new H.map.render.harp.Style('https://example.com/styles/night.json'); // Create a vector layer using the style var vectorLayer = platform.getOMVService().createLayer(style); var map = new H.Map( document.getElementById('map'), vectorLayer, // pass the styled layer directly { center: { lat: 52.5148, lng: 13.3984 }, zoom: 13, pixelRatio: window.devicePixelRatio || 1, } ); ``` ``` -------------------------------- ### 3D Extruded Objects Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Extrude circles and polygons to 3D buildings by setting the `extrusion` property (height in metres). Requires a tilted view using `setLookAtData`. ```APIDOC ## 3D Extruded Objects — `extrusion` style property ### Description Extrude circles and polygons to 3D buildings by setting the `extrusion` property (height in metres). Requires a tilted view using `setLookAtData`. ### Usage ```js // Set a tilted 3D view map.getViewModel().setLookAtData({ tilt: 38, heading: 245 }); // Extruded circle (column / cylinder) var column = new H.map.Circle( { lat: 48.8726, lng: 2.3357 }, 2, // radius in metres { extrusion: 40, style: { fillColor: '#0297A0', strokeColor: 'none' } } ); // Extruded polygon (building) var building = new H.map.Polygon( new H.geo.Polygon( new H.geo.LineString([48.8727, 2.3357, 0, 48.8730, 2.3362, 0, 48.8732, 2.3353, 0]) ), { extrusion: 90, style: { strokeColor: 'none' } } ); map.addObjects([column, building]); ``` ``` -------------------------------- ### Render a Circle on the Map Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Use `H.map.Circle` to draw a circular region with a specified center and radius. Customize stroke and fill styles. ```javascript map.addObject(new H.map.Circle( { lat: 28.6071, lng: 77.2127 }, // New Delhi 1000, // radius in metres { style: { strokeColor: 'rgba(55, 85, 170, 0.6)', lineWidth: 2, fillColor: 'rgba(0, 128, 0, 0.7)', }, } )); ``` -------------------------------- ### Capture Map Viewport to Canvas Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Renders the current map viewport, optionally including UI elements, to an HTML5 canvas asynchronously. Can capture the entire viewport or a specific area. ```javascript function captureMap(map, ui, resultContainer) { // Arguments: callback, [ui components], x, y, width, height // Omit x/y/width/height to capture the entire viewport map.capture( function (canvas) { if (canvas) { resultContainer.innerHTML = ''; resultContainer.appendChild(canvas); } else { resultContainer.textContent = 'Capture not supported in this mode'; } }, [ui], // include UI (scale bar, zoom controls, etc.) 50, 50, // top-left origin within viewport 500, 200 // width and height of capture area ); } ``` -------------------------------- ### Display GeoJSON Data on Map Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Parses and displays GeoJSON data from a URL onto the map. Allows for per-feature style overrides. ```javascript function showGeoJSONData(map) { var reader = new H.data.geojson.Reader( 'https://example.com/data/region.json', { style: function (mapObject) { if (mapObject instanceof H.map.Polygon) { mapObject.setStyle({ fillColor: 'rgba(255, 0, 0, 0.5)', strokeColor: 'rgba(0, 0, 255, 0.2)', lineWidth: 3, }); } }, } ); reader.parse(); map.addLayer(reader.getLayer()); } ``` -------------------------------- ### Marker Clustering Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Aggregates large sets of point data into cluster nodes for performance and clarity using `H.clustering.Provider` and `H.map.layer.ObjectLayer`. ```APIDOC ## Marker Clustering — `H.clustering.Provider` / `H.map.layer.ObjectLayer` ### Description Aggregate large sets of point data into cluster nodes for performance and clarity. Requires the optional `mapsjs-clustering.js` module. ### Usage Include the `mapsjs-clustering.js` module in your HTML: ```html ``` ### Function Signature `startClustering(map, data)` ### Parameters #### `map` (H.Map) The HERE Map instance. #### `data` (Array) An array of data points, where each point is an object with `latitude` and `longitude` properties. ### Code Example ```js function startClustering(map, data) { // Convert raw data into DataPoint objects var dataPoints = data.map(function (item) { return new H.clustering.DataPoint(item.latitude, item.longitude); }); // Create the clustering provider var clusteredDataProvider = new H.clustering.Provider(dataPoints, { clusteringOptions: { eps: 32, // neighbourhood radius in pixels minWeight: 2, // minimum points to form a cluster }, }); // Wrap in a layer and add to the map map.addLayer(new H.map.layer.ObjectLayer(clusteredDataProvider)); } // Example usage: // var airports = [{ latitude: 51.477, longitude: -0.461 }, ...]; // startClustering(map, airports); ``` ``` -------------------------------- ### Include HERE Maps API v3/3.2 CDN Scripts Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Required CDN scripts for HERE Maps API v3/3.2. Ensure these are included in your HTML. ```html ``` -------------------------------- ### GeoJSON Overlay Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Parse and display GeoJSON data directly on the map with optional per-feature style overrides using H.data.geojson.Reader. ```APIDOC ## GeoJSON Overlay — `H.data.geojson.Reader` ### Description Parse and display GeoJSON data directly on the map with optional per-feature style overrides. ### Usage ```js function showGeoJSONData(map) { var reader = new H.data.geojson.Reader( 'https://example.com/data/region.json', { style: function (mapObject) { if (mapObject instanceof H.map.Polygon) { mapObject.setStyle({ fillColor: 'rgba(255, 0, 0, 0.5)', strokeColor: 'rgba(0, 0, 255, 0.2)', lineWidth: 3, }); } }, } ); reader.parse(); map.addLayer(reader.getLayer()); } ``` ``` -------------------------------- ### Reverse Geocoding — `platform.getSearchService().reverseGeocode` Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Resolves a latitude and longitude back to a human-readable address. It can also search within a specified radius around the given coordinates and limit the number of results. ```APIDOC ## Reverse Geocoding — `platform.getSearchService().reverseGeocode` ### Description Resolve a latitude/longitude back to a human-readable address. ### Usage ```js function reverseGeocode(platform) { var searchService = platform.getSearchService(); searchService.reverseGeocode( { at: '52.5309,13.3847,150', // lat,lng,radius in metres limit: '1', }, function onSuccess(result) { result.items.forEach(function (item) { var addr = item.address; console.log(addr.label); // e.g. "Invalidenstraße 116, 10115 Berlin, Germany" map.addObject(new H.map.Marker(item.position)); }); }, function onError(err) { alert("Reverse geocoding failed: " + err); } ); } ``` ``` -------------------------------- ### Driving Route Calculation Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Calculates a turn-by-turn car route between two points, returning polyline geometry and action instructions. ```APIDOC ## Driving Route — `platform.getRoutingService().calculateRoute` ### Description Calculate a turn-by-turn car route between two points. The response contains sections with flexible-polyline encoded geometry and action instructions. ### Method Signature `platform.getRoutingService().calculateRoute(options, onSuccess, onError)` ### Parameters #### `options` (Object) - `routingMode` (string) - Specifies the routing mode (e.g., 'fast'). - `transportMode` (string) - Specifies the transport mode (e.g., 'car'). - `origin` (string) - The starting point for the route (latitude,longitude). - `destination` (string) - The ending point for the route (latitude,longitude). - `return` (string) - Specifies the data to be returned (e.g., 'polyline,turnByTurnActions,actions,instructions,travelSummary'). #### `onSuccess` (Function) Callback function executed when the route calculation is successful. #### `onError` (Function) Callback function executed when the route calculation fails. ### Request Example ```js router.calculateRoute({ routingMode: 'fast', transportMode: 'car', origin: '52.5160,13.3779', // Brandenburg Gate destination: '52.5206,13.3862', // Friedrichstraße station return: 'polyline,turnByTurnActions,actions,instructions,travelSummary' }, onSuccess, onError); ``` ### Response Example (onSuccess) ```js { "routes": [ { "sections": [ { "polyline": "...", // Flexible polyline encoded geometry "travelSummary": { "length": 1234, // Distance in meters "duration": 300 // Duration in seconds }, "actions": [...], // Turn-by-turn actions "instructions": [...] // Navigation instructions } ] } ] } ``` ``` -------------------------------- ### Calculate Driving Route with HERE Maps API Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Calculates a turn-by-turn car route between two points. The response includes polyline geometry and turn-by-turn instructions. Ensure the platform object is initialized. ```javascript function calculateCarRoute(platform) { var router = platform.getRoutingService(); router.calculateRoute( { routingMode: 'fast', transportMode: 'car', origin: '52.5160,13.3779', // Brandenburg Gate destination: '52.5206,13.3862', // Friedrichstraße station return: 'polyline,turnByTurnActions,actions,instructions,travelSummary', }, function onSuccess(result) { var route = result.routes[0]; route.sections.forEach(function (section) { // Decode the flexible polyline into a LineString var lineString = H.geo.LineString.fromFlexiblePolyline(section.polyline); var polyline = new H.map.Polyline(lineString, { style: { lineWidth: 4, strokeColor: 'rgba(0, 128, 255, 0.7)' }, }); map.addObject(polyline); map.getViewModel().setLookAtData({ bounds: polyline.getBoundingBox() }); // Log total distance and duration console.log( 'Distance:', section.travelSummary.length, 'm', '| Duration:', Math.floor(section.travelSummary.duration / 60), 'min' ); }); }, function onError() { alert("Can't reach routing service"); } ); } ``` -------------------------------- ### Marker Clustering with HERE Maps API Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Aggregates large sets of point data into cluster nodes for better performance and clarity on the map. Requires the 'mapsjs-clustering.js' module to be included. ```html ``` ```javascript function startClustering(map, data) { // Convert raw data into DataPoint objects var dataPoints = data.map(function (item) { return new H.clustering.DataPoint(item.latitude, item.longitude); }); // Create the clustering provider var clusteredDataProvider = new H.clustering.Provider(dataPoints, { clusteringOptions: { eps: 32, // neighbourhood radius in pixels minWeight: 2, // minimum points to form a cluster }, }); // Wrap in a layer and add to the map map.addLayer(new H.map.layer.ObjectLayer(clusteredDataProvider)); } // Example: cluster airport coordinates // airports = [{ latitude: 51.477, longitude: -0.461 }, ...] startClustering(map, airports); ``` -------------------------------- ### Fit Map Viewport to Geographic Bounds Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Fits the map's visible viewport to a specified geographic bounding box or the bounding box of a group of objects. Useful for ensuring a specific region is displayed. ```javascript // Display the area around Boston (top-left lat/lng, bottom-right lat/lng) var bbox = new H.geo.Rect(42.3736, -71.0751, 42.3472, -71.0408); map.getViewModel().setLookAtData({ bounds: bbox }); // Alternatively, zoom to fit a group of objects var group = new H.map.Group(); group.addObjects([ new H.map.Marker({ lat: 43.7, lng: -79.4 }), // Toronto new H.map.Marker({ lat: 42.35805, lng: -71.0636 }), // Boston new H.map.Marker({ lat: 38.8951, lng: -77.0366 }), // Washington ]); map.addObject(group); map.getViewModel().setLookAtData({ bounds: group.getBoundingBox() }); ``` -------------------------------- ### Draw a Rectangle on the Map Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Utilize `H.map.Rect` with a `H.geo.Rect` bounding box to draw a rectangular area. Styles for fill and stroke can be applied. ```javascript var bounds = new H.geo.Rect(37.829, -122.426, 37.824, -122.420); map.addObject(new H.map.Rect(bounds, { style: { fillColor: 'rgba(55, 85, 170, 0.1)', strokeColor: 'rgba(55, 85, 170, 0.6)', lineWidth: 8, }, })); ``` -------------------------------- ### Circle — `H.map.Circle` Source: https://context7.com/heremaps/maps-api-for-javascript-examples/llms.txt Renders a circular region on the map centered at a given coordinate with a specified radius in meters. It allows customization of the circle's style, including stroke and fill colors and line width. ```APIDOC ## Circle — `H.map.Circle` ### Description Render a circular region on the map centred at a given coordinate with a radius in metres. ### Usage ```js map.addObject(new H.map.Circle( { lat: 28.6071, lng: 77.2127 }, // New Delhi 1000, // radius in metres { style: { strokeColor: 'rgba(55, 85, 170, 0.6)', lineWidth: 2, fillColor: 'rgba(0, 128, 0, 0.7)', }, } )); ``` ```