Рисование гладкой полилинии на картах Google - PullRequest
0 голосов
/ 16 января 2019

Я использую googlemaps api для рисования полилинии между координатами (Lat / Lang), полученными с устройства GPS, использующего Angular 6. Координаты обновляются с интервалом в 10 секунд. Я использую класс Polyline в Google Maps для рисования линии, но проблема в том, что каждый раз, когда он рисует линию между двумя точками (новая точка и старая точка), он мгновенно перепрыгивает между точками вместо того, чтобы рисовать гладкую анимированную траекторию, как Uber. , Мне нужно рисовать плавный путь между точками.

Я сейчас читаю координаты из файла JSON ..

Кто-нибудь может мне помочь с этим .?

Вот код для рисования полилинии:

import { Component } from '@angular/core';
import { ViewChild } from "@angular/core";

import { } from 'googlemaps'
// import { } from '@types/googlemaps'
import { DataFetcherService } from "src/app/services/data-fetcher.service";

import { map } from 'rxjs/operators';
import { of, from } from "rxjs";
import { Promise } from "q";
// import {} fr

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

  title = 'maps-app';
  @ViewChild('gmap') gmapElement: any;
  map: google.maps.Map;
  snappedPolyline: google.maps.Polyline;
  icon = "http://maps.google.com/mapfiles/ms/micons/blue.png";
  private snappedCoordinates: any[] = [];
  index = 1;
  markerOffset = 0;
  prevMarkerOffset = 0;
  prevlatlng;
  latlng;
  ngOnInit() {

      this.initMap()

     // Define the symbol, using one of the predefined paths ('CIRCLE')
      // supplied by the Google Maps JavaScript API.
      var lineSymbol = {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8,
        strokeColor: '#393'
      };

    this.snappedPolyline = new google.maps.Polyline({
        path: this.snappedCoordinates,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2,
        icons: [{
          icon : lineSymbol,
          offset: '100%'
        }],
        map: this.map
      })
      this.setCenter();
  }
   constructor (private dataFetcher: DataFetcherService){ }
  initMap(){
    let mapProp = {
      center: new google.maps.LatLng(8.89443000002,76.61418),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
  }

  ngAfterContentInit(){

    console.log("After content init")
    this.dataFetcher.fetchJSONData('assets/data/latlangobj.json').subscribe(data => {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(8.89443000002,76.61418),
        map: this.map,
        icon: this.icon,
        title: 'Center !'
      });

      data.forEach((cordinates) => {

        setTimeout(() =>
        {       
          console.log("setTimeout(), this.index * 12000 :", this.index * 12000)
          this.prevlatlng = this.latlng          
          this.latlng = new google.maps.LatLng(cordinates.lat, cordinates.lng)
          this.snappedPolyline.getPath().push(this.latlng);
          this.prevlatlng = this.latlng
          this.snappedPolyline.setMap(this.map);
          this.updateMarkerPosition(this.map, marker, cordinates.lat, cordinates.lng);
        }, this.index * 500);  // 6k *  this.index
        ++this.index
      });  
      }, // outer-observable ends here
     err => console.error(err)
    )
  }

  calculateDistances(start, end) {

    var stuDistances = {};
    const metres = google.maps.geometry.spherical.computeDistanceBetween(start, end);    // distance in metres
        return metres
    }

      // update marker position
      updateMarkerPosition(map, marker, lat, lon) {
          console.log("MoveMarker()")
          try {
          marker.setPosition(new google.maps.LatLng(lat, lon));
          map.panTo(new google.maps.LatLng(lat, lon));
        } catch (e) {}
      }
    // set the center to the updated latlang
  setCenter() {
    this.map.setCenter(new google.maps.LatLng(8.89443000002,76.61418));

    let marker = new google.maps.Marker({
      position: new google.maps.LatLng(8.89443000002,76.61418),
      map: this.map,
      icon: this.icon,
      title: 'Center !'
    });
}
...