Angular provides a powerful set of tools and features for building web applications. You can create an even more engaging experience for your users by combining these features with HERE SDKs and APIs.
For example, you can integrate HERE Maps with Angular to display interactive maps, geocode addresses, calculate routes, and more, all within the context of your Angular application.
See the following sections for step-by-step instructions on how to create a simple interactive map within the context of an Angular application:
Sign up for a HERE developer account and obtain your API credentials. For more information, see Get started.
Install Angular CLI
Facilitate the development of a new Angular application by using the Angular CLI.
In the Command Prompt, enter the following command to install Angular CLI:
npminstall-g @angular/cli
Initiate a new Angular project by entering the following command:
ng new jsapi-angular &&cd jsapi-angular
Install Angular routing and use the CSS stylesheet by answering the corresponding prompts, as shown in the following example:
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
Result: The system creates a new jsapi-angular directory, with the Angular components residing in the src sub-directory. The jsapi-angular directory has the following structure:
Install the maps-api-for-javascript NPM package which is hosted at https://repo.platform.here.com/ by adding a registry entry to the NPM configuration through the following command:
npm config set @here:registry https://repo.platform.here.com/artifactory/api/npm/maps-api-for-javascript/
Install the package from the @here namespace by entering the following command:
npminstall @here/maps-api-for-javascript
Navigate to the jsapi-angular folder, and then open the tsconfig.json file in a preferred text editor.
In the tsconfig.json file, add the following setting under angularCompilerOptions:
"allowSyntheticDefaultImports":true
Optional: To verify that you completed the setup successfully, perform the following actions:
Enter the following command:
ng serve
Result: This command launches a development server with the "hot reload" functionality.
Initiate the Angular application by navigating to the http://localhost:4200/ address in the browser.
Result: The browser displays the Angular welcome screen with the jsapi-angular is running! message.
Add a static map component
In your Angular application, generate a static map by creating a component that contains an H.Map namespace instance. This component renders the map through the corresponding container.
In the Angular CLI, generate the jsmap component by entering the following command:
ng generate component jsmap
Result: The command creates a jsmap folder in the src/app directory. The folder contains all the files required to build the component:
Navigate to the jsapi-angular/src/app/jsmap directory, and then open the jsmap.component.ts file.
In the jsmap.component.ts file, replace the default code with the following code:
import{ Component, ViewChild, ElementRef }from'@angular/core';importHfrom'@here/maps-api-for-javascript';
@Component({selector:'app-jsmap',templateUrl:'./jsmap.component.html',styleUrls:['./jsmap.component.css']})exportclassJsmapComponent{private map?:H.Map;
@ViewChild('map') mapDiv?: ElementRef;ngAfterViewInit():void{if(!this.map &&this.mapDiv){// Instantiate a platform, default layers and a map as usual.const platform =newH.service.Platform({apikey:'{YOUR_API_KEY}'});const layers = platform.createDefaultLayers();const map =newH.Map(this.mapDiv.nativeElement,// Add type assertion to the layers object... // ...to avoid any Type errors during compilation.(layers as any).vector.normal.map,{pixelRatio: window.devicePixelRatio,center:{lat:0,lng:0},zoom:2,},);this.map = map;}}}
This code imports the HERE Maps API for JavaScript library and instantiates the map through the ngAfterViewInit hook.
Open the jsmap.component.html file, and then replace the file contents with the following code:
<div#mapid="map"></div>
Open the jsmap.component.css file, and then add the following style:
#map{width: 100%;height: 300px;}
In the jsapi-angular/src/app directory, open the app.component.html file, and then replace the file content with following code:
<app-jsmap></app-jsmap>
Verify that the map renders correctly by navigating to the http://localhost:4200/ address in the browser.
Result: The browser renders a static map at the zoom level 2 and 0 latitude and longitude, in the viewport that is 300 pixels high and takes 100% of the enclosing container's width, similar to the following example:
Resize the map
A static map with a predetermined size cannot be changed during runtime, as indicated by the highlighted area in the following figure:
Figure 1. Static Map component
You can improve a static map by adding dynamic resizing to make the map canvas react and adapt to the changes in the viewport size, for example, when the user expands the browser window.
To achieve that, the map needs an explicit resize() method call to adjust to the new dimensions of the container.
This example uses simple-element-resize-detector to demonstrate how you can resize a map within an Angular component.
In Angular CLI, switch your working directory to the jsapi-angular project directory.
From the src/app/jsmap directory, open the jsmap.component.ts file, and then adjust the import statements by adding the simple-element-resize-detector library, as shown in the following example:
The mapposition component has three input fields: zoom, latitude and longitude. The new code introduces a change event listener that redispatches events for each input field to the parent component.
From the src/app/mapposition/ directory, open the mapposition.component.ts fie, and then replace the file content with the following code:
This TypeScript part of the component uses the @Output decorator and the EventEmitter class to notify the parent component about the changes in the user input.
From the src/app directory, open the app.component.html file, and then replace the file content with the following code:
Within the JsmapComponent class, after the existing ngAfterViewInit hook definition, add @Input decorators for zoom, latitude, and longitude, and then add the ngOnChanges hook definition, as shown in the following code snippet:
Result: Now, your Angular application can take your input with the help of the mapposition component, store the state in the app component, and then update the jsmap component so that the map responds to the input.
The following example demonstrates how the Angular application responds to the input by setting the coordinates to center the map on Berlin, and then increasing the zoom level:
Enable dragging and zooming
Further increase the interactivity of your map by enabling map manipulation in the form of dragging or zooming in or out of the view.
To achieve this behaivor, add the mapviewchange listener to the H.Map instance, and then update the app state with the help of the EventEmitter.
In the app.component.ts file, update the App state by adding the following code:
Result: The resulting application consist of the interactive map and input fields. Now, when you interact with the map, the application automatically updates the input fields, as shown in the following example:
Add markers
The Angular application that you just created might serve as a template for adding further customizations or extensions that suit your business objectives. For example, you can add map markers to provide a quick and efficient way to visually represent the location of a point of interest on a map.
In the jmaps.component.ts file, set the modify the map property to center on the area where you want to place the markers, as shown in the following example:
const map =newH.Map(this.mapDiv.nativeElement,(layers as any).vector.normal.map,{pixelRatio: window.devicePixelRatio,// In this example, the map centers on// Luxembourg City, with the zoom level of 16:zoom:16,center:{lat:49.6107,lng:6.1314}},);
Define a variable storing coordinates for each point of interest that you want to mark on the map, as shown in the following example:
// This array stores coordinates of some interesting landmarks in Luxembourg City:const landmarks =[{name:'Notre-Dame Cathedral',lat:49.610364,lng:6.129416,},{name:'Grand Ducal Palace',lat:49.611204,lng:6.130720},{name:'Casemates du Bock',lat:49.611847,lng:6.131925},{name:'Adolphe Bridge',lat:49.6083,lng:6.127109}];
Create a marker for each landmark in the landmarks array:
This code snippet sets each marker's data to the landmark name, and adds the marker to the map object using the addObject method.
Result: The map in your Angular application now centers on Luxembourg City and displays markers, as shown in the following figure:
Customize markers
You can control marker look and feel by providing custom icons for your markers. This example uses locally stored marker icons for simplicity.
In the src/app/assets directory, create a new folder called images.
For each landmark in the landmarks array, add a property called label, as shown in the following example:
const landmarks =[{name:'Notre-Dame Cathedral',lat:49.610364,lng:6.129416,label:'NDC'},{name:'Grand Ducal Palace',lat:49.611204,lng:6.130720,label:'GDP'},{name:'Casemates du Bock',lat:49.611847,lng:6.131925,label:'CdB'},{name:'Adolphe Bridge',lat:49.6083,lng:6.127109,label:'AB'},];
For each landmark, create a custom icon that follows these naming conventions: marker-<label_value>.png, and then store the icon in the src/app/assets/images directory.
Update the marker generation code to use custom icons:
landmarks.forEach(landmark=>{// For each marker, select the icon based on the corresponding landmark label:const icon =newH.map.Icon('/assets/images/marker-'+ landmark.label +'.png',// Adjust the marker size to your needs: {size:{w:80,h:80}});const marker =newH.map.Marker({lat: landmark.lat,lng: landmark.lng },{data: landmark.name,icon: icon });
map.addObject(marker);});
Result: The map now displays custom markers, as shown in the following figure: