0

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

kboul
  • 13,836
  • 5
  • 42
  • 53
Nithya
  • 39
  • 2
  • 8

2 Answers2

0

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

kboul
  • 13,836
  • 5
  • 42
  • 53
0

It is obviously too late to answer the original question, but if anybody gets here with the same issue, here is the solution.

The origin of the problem is that when we are trying to execute Angular navigation directly in the Leaflet event callback. But Leaflet map with its markers is outside Angular zone (= execution context):

marker.on('click', () => { // we are in Leaflet
    this.router.navigate('/dashboard'); // but this is Angular
});

So the solution is to run the navigation code from Angular zone:

    marker.on('click', () => { 
        this._ngZone.run(() => { // here we are back in Angular
            this.router.navigate('/dashboard'); 
        });
    });
    

Don't forget to include private _ngZone: NgZone, in component constructor.

For more detailed explanation check this one. The message in the title is the one you see as warning in console when trying to execute the first code section above.