我想用点对点的方向来实现谷歌地图,但是当我运行代码时,地图上没有显示两点之间的图形路线,我希望在地图上显示两点之间的路线地图(蓝色路线)。问题是否与API有关?我的html代码如下所示:
<ion-header>
<ion-navbar>
<ion-title> Map </ion-title>
<ion-buttons end>
<button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>
Add Marker</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<ion-card>
<ion-card-content>
<div #directionsPanel></div>
</ion-card-content>
</ion-card>
<div #map id="map"></div>
</ion-content>
我的TS文件如下:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google;
@Component({
selector: 'gmap-page',
templateUrl: 'gmap.html'
})
export class GmapPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
@ViewChild('directionsPanel') directionsPanel: ElementRef;
constructor(public navCtrl: NavController, public geolocation: Geolocation) {
}
ionViewDidLoad(){
this.loadMap();
this.startNavigating();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}, (err) => {
console.log(err);
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
startNavigating(){
let directionsService = new google.maps.DirectionsService;
let directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(this.map);
directionsDisplay.setPanel(this.directionsPanel.nativeElement);
directionsService.route({
origin: 'adelaide',
destination: 'adelaide oval',
travelMode: google.maps.TravelMode['DRIVING']
}, (res, status) => {
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(res);
} else {
console.warn(status);
}
});
}
}
谢谢。