Facing difficulty with angular 2 google map

2019-09-11 20:39发布

问题:

I have created google map using Sebastian example. I can able to load the map. But my requirement is to search the places which I type in search box and then it should put the marker in the map. I can able to search the place also, but could not locate it in the map. If I scroll the map marker will come automatically. Below is my code. Suggest me if you know any other way of doing it or any other example.

            <div class="fieldMap">
                    <sebm-google-map 
                    [latitude]="lat"
                    [longitude]="lng"
                    [zoom]="zoom"
                    [disableDefaultUI]="true"
                    [zoomControl]="true"
                    [disableDefaultUI]="false"
                    (mapClick)="mapClicked($event)">

                    <sebm-google-map-marker 
                    *ngFor="let m of markers; let i = index"
                    [latitude]="m.lat"
                    [longitude]="m.lng"
                    [label]="m.label">
                    </sebm-google-map-marker>                   
            </sebm-google-map> 

And the script part is

  getAddress(place:Object) { 
    this.markers = [];
    var address = this.step1Data.map_address;
    if (!address) return false;
    var geocoder = new google.maps.Geocoder();
    var that = this;

    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            that.lat =  location.lat();
            that.lng = location.lng();
            that.markers.push({
                lat: that.lat,
                lng: that.lng,
                label: 'A',
                draggable: false
            })
        } 
    });
}

回答1:

Problem was with time out. If I push coords with setTimeout later it will work properly.

geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            that.lat = location.lat();
            that.lng = location.lng();
        } else {
            that.step1["gmapError"] = "Geocode was not successful for     the following reason: " + status;
        }
    });

    setTimeout(() => {
            this.markers.push({
                lat: that.lat,
                lng: that.lng,
                label: 'A',
                draggable: false
            });
    }, 100);


标签: angular