javascript - 如何使用谷歌地图在setinterval后保留缩放和刷新

标签 javascript angular google-maps google-maps-api-3

您好,我正在使用 Angular 网络开发跟踪应用程序。每 30 秒,我就能够从服务器渲染数据,我的问题是,当我更新坐标时,它会刷新自动缩放,我的意思是假设我正在查看 map 缩放:16 通过在 setinterval init 之后放大,它显示缩放级别@10 那么我如何在刷新后保留缩放和居中以及有什么方法可以在不使用设置间隔的情况下更新标记 下面是我的代码

{
    "page": 2,

    "data": [
        {
            "id": 4,
            "first_name": "Eve",
            "last_name": "Holt",
            "lat":"25.6599899",
            "lng":"45.3664646",
            "status":"0"

        },
        {
            "id": 5,
            "first_name": "Charles",
            "last_name": "Morris",
            "lat":"25.99899",
            "lng":"45.4646",
             "status":"1"

        },
        {
            "id": 6,
            "first_name": "Tracey",
            "last_name": "Ramos",
            "lat":"25.2339899",
            "lng":"45.56664646",
            "status":"1"

        }
    ]
}

import {Component, OnDestroy, OnInit, ViewChild, ViewContainerRef} from '@angular/core';
import {DataService} from '../service/data.service';
import {Router} from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import {Alert} from 'selenium-webdriver';






declare var google: any;

@Component({
  selector: 'app-tracking',
  templateUrl: './tracking.component.html',
  styleUrls: ['./tracking.component.css']
})
export class TrackingComponent implements OnInit, OnDestroy {


  public LocData: any;
  public DriversData: any;
  public location: any;
  public drivers: any;
  public mapObject: any;
  public markers: any = [];
  mapData: any;

  markerName: any;


  timer: any;

  response: any;
   public zoomlevel:any=13;

  public latlng:any={lat:25.204849,lng:55.270783};

  public locLatlng:any;
  public loczoomlevel:any;

  public getloclng:any;
  public getzoomlevel:any;
  public mapOptions:any;
  public mapCenter:any;




  constructor(public serv: DataService, private router: Router, public spinner: NgxSpinnerService) {

    // this is for loading the locations data
    this.spinner.show();
    this.serv.LoadLocation().subscribe(res => {
      this.spinner.hide();
      this.LocData = res.Data;
     // console.log(this.LocData);
      this.location = this.LocData[0].Id;
      this.onLoChange(this.location);
    }, err => {
      this.spinner.hide();

    });

   //
    this.timer = setInterval(() => {this.getMapData(this.drivers, this.location); }, 30000);




    this.getMapData(this.drivers, this.location);



  }


  onLoChange(data) {
   // console.log('Location', data);
    this.driverLoadData(data);
    //this.location = event.target.value;
    this.getMapData(this.drivers, this.location);
  }

  onDriverChange(event) {
    //console.log('Driver Id', event.target.value);
    this.drivers = event.target.value;
    this.getMapData(this.drivers, this.location);

  }

  driverLoadData(data) {
    this.spinner.show();
    this.serv.LoadDrivers(data).subscribe(res => {
      this.spinner.hide();
      //console.log(res);
      this.DriversData = res.Data;

      this.drivers = this.DriversData[0].Id;

    }, err => {
      this.spinner.hide();
      alert('Unable to load Driver Data');
    });

  }





  getMapData(data, dataOne) {
   // this.spinner.show();
    this.serv.getMapData(data, dataOne).subscribe(res => {
      //this.spinner.hide();
      this.deleteMarkers();



      debugger;

      if (res.Data && res.Data.length > 0) {
        // do something
        this.mapData = res.Data;
       // console.log(JSON.stringify(this.mapData));
        // rendering markers

        if (this.mapData != null && this.mapData.length > 0) {
          for (let i = 0; i < this.mapData.length; i++) {
            this.latlng = {lat: parseFloat(this.mapData[i].latitude), lng: parseFloat(this.mapData[i].longitude)};
            this.addMarker(this.latlng, this.mapObject, this.mapData[i].Name);
            this.markerName = this.mapData[i].Name;


          }
        }
      } else {

       // this.response = 'No Data Exist';
        alert('No Data Exist');
      }

    }, err => {
      //this.spinner.hide();
      alert('Unalbe to display data');
    });


  }

  addMarker(latlng, mapobj, markerLabel) {
    var marker = new google.maps.Marker({
      position: latlng,
      label: '',
      map: mapobj,
//animation: google.maps.Animation.DROP,
    });




    const infowindow = new google.maps.InfoWindow({
      content: markerLabel
    });

    google.maps.event.addListener(marker, 'click', function() {
     // infowindow.open(Map,marker);
    });

    infowindow.open(Map, marker);





    const styless = [
      {
        "featureType": "poi.attraction",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },

      {
        "featureType": "poi.medical",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "poi.park",
        "elementType": "labels.text",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "poi.place_of_worship",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "poi.school",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "poi.sports_complex",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      }
    ]

    mapobj.setOptions({styles: styless});




    // This is for set postion for the marker after getting dynamic data it posittions to the point
   mapobj.setZoom(14);
   mapobj.panTo(marker.position);
    this.markers.push(marker);

  }





// Sets the map on all markers in the array.
  setMapOnAll(map) {
    for (let i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(map);
      this.markers[i].setPosition(this.markers[i].position);

    }
  }

  // Removes the markers from the map, but keeps them in the array.
  clearMarkers() {
    this.setMapOnAll(null);
  }


  // Deletes all markers in the array by removing references to them.
  deleteMarkers() {
    this.clearMarkers();
    this.markers = [];
  }





  ngOnInit() {


   this.mapOptions ={

      zoom:this.zoomlevel,
      center: this.latlng,
      gestureHandling: 'greedy'
   }

    this.mapObject = new google.maps.Map(document.getElementById('googleMap'),this.mapOptions );

    var trafficLayer = new google.maps.TrafficLayer();
    trafficLayer.setMap(this.mapObject);

    this.addMarker(this.latlng, this.mapObject, 'Current Location');



  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }




}

最佳答案

检查event-properties并使用map.getZoom()动态获取缩放级别。 更新您的 addMarker 函数

  addMarker(latlng, mapobj, markerLabel,zoomLevel){
    var marker = new google.maps.Marker({
      position: latlng,
      label: '',
      map: mapobj,
      zoom:zoomLevel,
      //animation: google.maps.Animation.DROP,
    });
  }

在循环内更新getMapData(data, dataOne)

if (this.mapData != null && this.mapData.length > 0) {
 this.zoomlevel=this.mapObject.getZoom();
  for (let i = 0; i < this.mapData.length; i++) {
    this.latlng = {
      lat: parseFloat(this.mapData[i].latitude),
      lng: parseFloat(this.mapData[i].longitude)
    };
    this.addMarker(this.latlng, this.mapObject, this.mapData[i].Name,this.zoomlevel);
    this.markerName = this.mapData[i].Name;
  }
}

更新您的ngOnInit

this.addMarker(this.latlng, this.mapObject, 'Current Location',this.zoomlevel);

stackblitz演示

使用 OP 数据更新了演示

Demo

关于javascript - 如何使用谷歌地图在setinterval后保留缩放和刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49517095/

相关文章:

javascript - 无法同时运行两个函数

testing - undefined 不是对象(评估 'config.forEach' )-Angular2 路由测试

Android Png 覆盖问题

javascript - 使用 Vuejs 求两个数字之和的按钮函数

javascript - 使用 PHP 登录和 OAuth2

node.js - 我如何从 ionic 存储返回我的对象

angular - 如何在 Angular 两个子组件之间进行通信?

android - 如何获取设备的当前位置?谷歌地图

ios - 我的位置按钮未出现在 View 中(Google map SDK、ios)

javascript - 在 chrome 扩展程序中收听选定的文本拖动事件