Search code examples
leafletangular7

Angular 7 routing not working when clicking on the leaflet marker


I am working with angular 7 and leaflet js for the map representation.

I want to navigate to another page when click on the marker. But routing is not working properly.

eg:

L.marker.on('click', function(){
    this.router.navigateByUrl('/dashboard');
});

when click on the marker, the url changed to '/dashboard' but the map still showing in the page.

when click on the html element, navigation working fine.

Could any one please help me on this.

Thanks in advance


Solution

  • You need to define the two routes and then listen to the marker on click event to be able to navigate.

    For instance have these two routes map and dashboard on app.module.ts and land on map view when initializing the app:

    const appRoutes: Routes = [
      { path: "map", component: MapComponent },
      { path: "dashboard", component: DashboardComponent },
      { path: "", redirectTo: "/map", pathMatch: "full" }
    ];
    
    @NgModule({
      declarations: [AppComponent, MapComponent, DashboardComponent],
      imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
      ...
    })
    

    and then add <router-outlet></router-outlet> on app.html to be able to navigate to different pages

    Then you might have a map component where the map will be held. Add the marker on the map, listen to the click event & navigate to dashboard page:

    L.marker([51.505, -0.09], this.markerIcon)
       .addTo(this.map)
       .on("click", e => {
            this.router.navigateByUrl("/dashboard");
       });
    

    I also added a button to navigate back to map component from the dashboard page

    Demo