简体   繁体   中英

How To Refresh Google Map In Angular?

I need to refresh google map every time I press the "show" button that changes the lat and lng.

I'm using AGM for the Google Map.

Here I'm getting the lat and lng I wanna see on the map:

onShow(_token: string) {
        var find = this.model.find(({ token }) => token === _token);

        this.postsService.setLat(find.lat);
        this.postsService.setLng(find.lng);

        console.log(
            this.postsService.getLat() + '    ' + this.postsService.getLng()
        );
    }

On the web page i have some locations. When I press "Show" button I want to see that location I point to on the map.

That's app.component.ts:

import { Component } from '@angular/core';
import { PostsService } from './posts.service';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
})
export class AppComponent {
    constructor(public postsService: PostsService) {}

    title = 'Location Project';
    lat: number = this.postsService.getLat();
    lng: number = this.postsService.getLng();
    zoom: number = 12;
}

The problem is that the map is created with lat and lng being undefined (and so the map shows a default point in the ocean). How can i refresh the map every time I change the lat and lng values?

app.component.html:

<app-header></app-header> <br /><br />

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
    <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>

<br /><br />

<app-post-list></app-post-list>

posts.service:

import { Location } from './post.model';
import { Injectable } from '@angular/core';
import { Subject, Observable, Subscription, from } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class PostsService {
    model: Location[] = [];

    constructor() {}

    private lat;
    private lng;

    setLat(lat) {
        this.lat = lat;
    }
    setLng(lng) {
        this.lng = lng;
    }
    getLat() {
        return this.lat;
    }
    getLng() {
        return this.lng;
    }
}

Here's a screenshot of some hardcoded lat and lng values, to show how it should appear.

Where are the map markers set? You must define markers with the new locations and set them on the map. I think you're showing lat and lng variables, but you're not setting them in your onShow method. You only call setLat, setLng method from the service but not updating the lat and lng variables!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM