如何在原生谷歌地图上以英里和公里为单位显示两个标记之间的距离? (Cordova,Ionic 3)

时间:2018-04-27 03:52:47

标签: cordova ionic-framework ionic2 ionic3 cordova-plugins

如何在离子原生谷歌地图上以英里和公里为单位显示两个标记之间的距离? 我想使用h3标签在地图的右上方显示数字。

并且有没有办法显示估计旅行时间?我需要估计步行和开车的时间。

任何示例代码都将受到赞赏。

谢谢,

1 个答案:

答案 0 :(得分:2)

我使用Google地图路线服务 API来显示两个地方之间的距离。

首先,使用以下方法安装Google地图库:

npm install @types/googlemaps --save-dev

现在转到node_modules然后转到@types并在Google maps文件夹中添加以下行:

declare module 'googlemaps';

现在,我们将使用Google Maps JavaScript库来获取有关这些地方的信息。因此,请在index.html文件中包含Google Maps js文件:

<script src="http://maps.google.com/maps/api/js?key=XXXXX=places"></script>
  • 上述脚本需要Google Maps API密钥。跟着这些步骤:
    • 转到https://console.developers.google.com
    • 创建新的Google项目并为项目指定适当的名称
    • 创建新项目后,它会将您重定向到API部分并点击Google Maps JavaScript API
    • 点击启用API。然后单击创建凭据并单击我需要的凭据?
    • 就是这样。它会为您提供Google Maps API密钥

然后安装geolocation插件以访问用户位置:

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

现在在 app.module.ts 文件中导入地理位置插件:

import { Geolocation } from '@ionic-native/geolocation';      
@NgModule({    
     ...   
     providers: [  Geolocation   ]  
     ... })

然后将Google地图类和地理位置插件导入 home.ts 文件:

import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';

import { googlemaps } from 'googlemaps';

现在将以下代码添加到 home.ts 文件中:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation';
import { googlemaps } from 'googlemaps';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})


export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  @ViewChild('directionsPanel') directionsPanel: ElementRef;

  map:any;
  latLng:any;
  markers:any;
  mapOptions:any;

  startService:any;
  autocompleteStart:any;

  endService:any;
  autocompleteEnd:any;

  directionsService = new google.maps.DirectionsService;
  directionsDisplay = new google.maps.DirectionsRenderer;
  start:any;
  end:any;
  travelType:any = 'DRIVING';

  //distance and duration
  distance:any='';
  duration:any='';

  constructor(private geolocation : Geolocation) { }

  ionViewDidLoad() {
    this.loadMap();
    this.startService = new google.maps.places.AutocompleteService();        
    this.autocompleteStart = [];
    this.endService = new google.maps.places.AutocompleteService();        
    this.autocompleteEnd = [];      
    this.start = '';
    this.end = '';
  }

  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {

      this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      console.log('latLng',this.latLng);

      this.mapOptions = {
        center: this.latLng,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }   

      this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);

    }, (err) => {
      alert('err '+err);
    });

  }

/*-----------------------Search Direction--------------------*/

  startSearch() {

    if (this.start == '') {
      this.autocompleteStart = [];
      return;
    }

    let self = this; 

    let config = { 
      input: this.start, 
      componentRestrictions: {  } 
    }

    this.startService.getPlacePredictions(config, function (predictions, status) {
      console.log('modal > getPlacePredictions > status > ', status);
      self.autocompleteStart = [];            
      predictions.forEach(function (prediction) {              
      self.autocompleteStart.push(prediction);
      });
    });

  }

  endSearch() {

    if (this.end == '') {
      this.autocompleteEnd = [];
      return;
    }

    let self = this; 

    let config = { 
      input: this.end, 
      componentRestrictions: {  } 
    }

    this.endService.getPlacePredictions(config, function (predictions, status) {
      console.log('modal > getPlacePredictions > status > ', status);
      self.autocompleteEnd = [];            
      predictions.forEach(function (prediction) {              
        self.autocompleteEnd.push(prediction);
      });
    });
  }

  chooseStart(item){
    console.log('item',item);
    this.start = item.description; 
    this.autocompleteStart = [];
  }

  chooseEnd(item){
    console.log('item',item);
    this.end = item.description;
    this.autocompleteEnd = [];
  }

/*--------------------Get Direction beteen to places-----------------------*/

  getDirections(){

    this.directionsDisplay.setMap(this.map);
    this.directionsDisplay.setPanel(this.directionsPanel.nativeElement);

    this.directionsService.route({
      origin : this.start,
      destination : this.end,
      waypoints: this.wayPoints,
      optimizeWaypoints: true,
      travelMode : this.travelType,
      provideRouteAlternatives: true,
    }, (response, status) => {
        if (status == google.maps.DirectionsStatus.OK) {
         this.directionsDisplay.setDirections(response);
          // Create a new DirectionsRenderer for each route
        for (var i = 0; i < response.routes.length; i++) {
            var dr = new google.maps.DirectionsRenderer();
            dr.setDirections(response);
            // Tell the DirectionsRenderer which route to display
            dr.setRouteIndex(i);
            dr.setMap(this.map);

            // Code ommited to display distance and duration
           let x = i+1;
            // Display the distance:
             this.distance += x +') '+ response.routes[i].legs[0].distance.text +', ' ;
             console.log('distance',this.distance);
            // Display the duration:
            this.duration += x +') '+ response.routes[i].legs[0].duration.text +', ' ;
            console.log('duration',this.duration);
        }

       // this.directionsDisplay.setDirections(response);
        console.log('response:-',response);
      } else {
        alert('Directions request failed due to ' + status);
      }
    });
  }

}

现在将以下代码添加到 home.html 文件中:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Map
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

<!--====================== For Get Direction ==========================-->

<form align="center">

    <ion-searchbar 
    [(ngModel)]="start" 
    name="start"
    [showCancelButton]="shouldShowCancel" 
    (ionInput)="startSearch()" 
    (ionCancel)="dismiss()"
    placeholder="Starting Places">
    </ion-searchbar>
    <ion-list>
        <ion-item *ngFor="let item of autocompleteStart" (click)="chooseStart(item)">
            {{ item.description }}
        </ion-item>
    </ion-list>


    <ion-searchbar 
    [(ngModel)]="end" 
    name="end"
    [showCancelButton]="shouldShowCancel" 
    (ionInput)="endSearch()" 
    (ionCancel)="dismiss()"
    placeholder="Ending Places">
    </ion-searchbar>
    <ion-list>
        <ion-item *ngFor="let item of autocompleteEnd" (click)="chooseEnd(item)">
            {{ item.description }}
        </ion-item>
    </ion-list>

    <button ion-button round (click)="getDirections()">GO</button>

</form>

<br>
  <div *ngIf="distance && duration">
    <b>Distance :- {{distance}}</b><br>
    <b>Duration :- {{duration}}</b>
  </div>

<br>
    <div #map id="map"></div>

    <ion-card>
        <ion-card-content>
            <div #directionsPanel></div>
        </ion-card-content>
    </ion-card>

</ion-content>