Tips for including HTML content in an agm-marker using Angular 2

In my Angular 2 application using agm map for vehicle tracking, I am looking for a way to customize the map marker. Specifically, I want to display the vehicle status by changing the color of the marker (green for running, red for stopped, yellow for idle) and also show the direction in which the vehicle is traveling.

After searching extensively, I was only able to find icons that could be added to the marker using iconUrl like this:

<agm-map>
    <agm-marker class="mapMarker" *ngFor="let device of devices;"  [latitude]="device.latitude" [longitude]="device.longitude" [iconUrl]="'/src/assets/arrow2.png'" [label]="device.name">
    </agm-marker>
</agm-map>

This resulted in an output that looked awkward as seen in this image: https://i.sstatic.net/HQZCa.png

I am seeking help to display HTML content on the marker instead of just an icon, similar to the desired output shown in this image: https://i.sstatic.net/RQKVA.png

Answer №1

If you're unfamiliar with agm and angular, fear not! Using standard Html/js tools, achieving this is relatively simple.

1.) Start by obtaining 2 coordinates from the vehicle in motion. You can then utilize the feature to display an arrow along a given path; 2.) Define a path (using the provided coords) with an arrow indicator, concealing the path so only the arrow is visible. 3.) Create a marker with an indirect label (with an offset) at the initial coordinate without actually showing the marker itself.

Below is an example for one vehicle. Feel free to adapt it or use specific elements as needed. Best of luck, Reinhard

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Polylines</title>
    <style>
      #map {height: 100%;}
      html, body {height: 100%;}
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 18.1, lng: 79.1},
          mapTypeId: 'terrain'
        });

///// Simple example for one vehicle //////

// Define the arrow to be displayed
var arrowGreen = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
fillColor: 'green',
fillOpacity: 0.8,
};

// Set two points in the driving direction of the vehicle
var dirCoordinates = [
          {lat: 18.0935, lng: 79.0741},
          {lat:  18.0936, lng: 79.0742},
         ];

// Define a polyline with arrow icon (visible in driving direction)
var poly = new google.maps.Polyline({
          path: dirCoordinates,
          strokeColor: 'green',
          strokeOpacity: 0,
          strokeWeight: 6,
  map: map
});
        poly.setOptions({icons: [{icon: arrowGreen, offset: '0'}]});

// Set the text as marker label without displaying the marker
var m = new google.maps.Marker({
  position: new google.maps.LatLng(dirCoordinates[0]),
  label: {
color: 'black',
fontWeight: 'bold',
text: 'TN28 AF 1416',
  },
   icon: {
url: 'none_marker.png',
anchor: new google.maps.Point(10, -25),
  },
map: map
});

// ...additional vehicles
}
    </script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
  </body>
</html>

Answer №2

I once attempted to change the marker style after binding data to the map, but agm did not allow it. However, I found a successful solution that worked for me.

It is possible that your data service can determine the direction of the vehicle.

In order to generate a list of markers, you will need a JSON data object array structured like this:

[
    {
        "latitude": 51.5238224,
        "longitude": -0.2485759,
        "markerUrl": "/assets/images/Map/20-red-icon.svg"
    },
    {
        "latitude": 51.238224,
        "longitude": -0.2485759,
        "markerUrl": "/assets/images/Map/30-green-icon.svg"
    },
    ,
    {
        "latitude": 51.4238224,
        "longitude": -0.2485759,
        "markerUrl": "/assets/images/Map/30-yellow-icon.svg"
    }
]

You should have multiple icons that can indicate the direction and status of a vehicle.

For example:

  • If a vehicle is headed north, use the icon "0-green-icon.svg"
  • If a vehicle is heading west, use the icon "270-green-icon.svg"
  • If a vehicle is going northwest, use the icon "315-green-icon.svg"
  • If a vehicle has stopped and is facing southwest, use the icon "225-red-icon.svg"

Ensure you have a variety of icons for different vehicle statuses and directions. The marker URL should be determined by the data from the service.

Answer №3

The issue at hand is not with AGM, but rather with the restrictions of the Google Maps API that prevent the use of HTML for markers, limiting it to only images. Unfortunately, current workarounds for creating custom HTML markers like this are not supported by AGM yet as indicated in this (ticket). If you truly require this functionality, you may need to implement a custom marker yourself using custom google overlays without relying on AGM.

Answer №4

Feel free to include

for example

<agm-marker [iconUrl]="icon.url" [latitude]="icon.latitude" [longitude]="icon.longitude"></agm-marker>

If you desire something different like a circular shape

or

<agm-circle *ngFor="data in circles"
              [latitude]="data.lat"
              [longitude]="data.lng"
              [circleDraggable]="true"
              [editable]="true"
              [fillColor]="'data.color'"
              [radius]="data.radius"
  >
  </agm-circle>

or rectangular

Answer №5

If you're struggling to find a more optimal solution, here's a workaround that might help:

Consider creating a new marker image with a transparent background and adding a bottom margin. You can then implement the same code provided in the original question.

For instance, you could try something like this: https://example.com/new-marker-image.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

Getting the button element in Angular when submitting a form

My web page contains multiple forms, each with a set of buttons. I want to incorporate a loading spinner on buttons after they are clicked. When using a regular click event, I am able to pass the button element: HTML <button #cancelButton class="butto ...

Alternative to bower_concat for NPM

bower_concat is an amazing tool. Simply add a bower package using: bower install something --save Then bower_concat will gather the javascript and CSS from that package and combine it into a bundle, resulting in vendor.js and vendor.css files that can be ...

How to implement a toggle button in an Angular 2 application with TypeScript

Currently, I'm working with angular2 in conjunction with typescript. Does anyone know how to generate a toggle button using on - off?. ...

Angular 5 Material Datepicker: A Sleek and Efficient Way to

I want the Angular Material Datepicker to remain open by default when the page is loaded, appearing within a section without needing to be triggered by an input field click. Currently, I am using a Datepicker that necessitates clicking on an input field. ...

An issue arose during the installation of the package 'npm i angularfire2'

I am currently working on an Angular project and I am trying to import AngularFireStorage using the following line of code: import { AngularFireStorage } from 'angularfire2/storage'; I attempted to do this by running the command npm i angularfire ...

able to utilize service within a loop

import { Component, Input, Output, OnInit, OnChanges } from '@angular/core'; import { ViewComponent } from '../view/view.component'; import { HitoService } from '../../services/hito.service'; @Component({ selector: 'ap ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

Updating validators on Angular reactive form controls as they change

I am working with a reactive form where I need to dynamically adjust the validators for the "password" and "confirm password" fields based on user input. I have set up a subscription to listen for changes in the password field's value, updating the va ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

What is the process for integrating uploaded files from a .NET Core API into my Angular application?

I'm having a problem displaying an image in my Angular application. This issue is encountered in both my profile.ts and profile.html files. public createImgPath = (serverPath: string) => { return `http://localhost:63040/${serverPath}`; } & ...

Avoiding the restriction of narrowing generic types when employing literals with currying in TypeScript

Trying to design types for Sanctuary (js library focused on functional programming) has posed a challenge. The goal is to define an Ord type that represents any value with a natural order. In essence, an Ord can be: A built-in primitive type: number, str ...

Ionic/Angular 2: Issue accessing object in the Page1 class - error caused by: Unable to retrieve the 'name' property as it is undefined

Currently, I am working on developing an application using Ionic and below is the code snippet: <ion-header> <ion-navbar> <button ion-button menuToggle> <ion-icon name="menu"></ion-icon> </button> &l ...

Angular 2 radio button problem with model-driven form

I'm facing a challenge with getting radio buttons to function correctly in my reactive form. Below is the code for my component: export class SettingsFormComponent implements OnInit { public sForm: FormGroup; public submitted: boolean; d ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Tips for determining if an array of objects, into which I am adding objects, contains a particular key value present in a different array of objects

I've been working on this and here is what I have tried so far: groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { ...

Angular Migration - Unable to locate a suitable version

I need to upgrade my application from Angular 10 to Angular 11. However, during the migration process, I encountered the following error: npm ERR! code ETARGET npm ERR! notarget No matching version found for @ruf/<a href="/cdn-cgi/l/email-protection" cl ...

Strategies for capturing a module's thrown exception during loading process

Is there a way to validate environment variables and display an error message on the page if the environment is found to be invalid? The config.ts file will throw an exception if the env variable is invalid. import * as yup from 'yup' console. ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

Mapping angular URLs with routes for the initial loading process

I recently encountered an issue with my Angular project that has multiple routes, such as /category/fruit/apple. When I try to access the full URL directly like http://myserver/category/fruit/apple, it returns a 404 error. This is because there is no confi ...