angular - Ionic 在位置上或基于经度和纬度设置标记

标签 angular ionic-framework

我正在学习一些教程,我想在当前位置设置标记。我正在获取用户的经度和纬度值,我需要在当前位置或可能的经度和纬度值上显示标记。还有一个问题,我可以在 map 上显示该位置的地址吗?在一些答案中,我检查了只有在中心设置标记的选项是否有任何选项可以在当前位置设置标记?

 constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, private locationAccuracy: LocationAccuracy) {

   this.catdata = this.navParams.get('for1');
   this.areadata = this.navParams.get('for2');
   console.log(this.catdata);
   console.log(this.areadata);

  this.locationAccuracy.canRequest().then((canRequest: boolean) => {
    if(canRequest) {
     // the accuracy option will be ignored by iOS
     this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
       () => {
         this.isGpsOn = true;
       },
       error => console.log('Error requesting location permissions', error)
     );
   }

  });

 this.addMarker();

  }

 ionViewDidLoad() {
   this.loadMap();
   }

 next(){
   this.navCtrl.push(Order4Page, {catdata:this.catdata,
                             areadata:this.areadata});
 }

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

    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
     console.log(position.coords.latitude);
        console.log(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,
          draggable: true,
           animation: google.maps.Animation.DROP,
                 //icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png',
        position: this.map.getCenter()
  });

  let content = "<h4>This is your current location?</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);
  });

   google.maps.event.addListener(marker, 'dragend', function()
         {
             this.markerlatlong = marker.getPosition();

             console.log("latlong   "+this.markerlatlong);
             console.log("lat    "+marker.getPosition().lat());
             console.log("long   "+marker.getPosition().lng());
         });
 }
}  

还有一件事还需要显示那个经纬度值的地址。

最佳答案

嘿,我正在分享 map 的完整实现 - latLng 和标记。

在您的 HTML 文件中。

<ion-header>
  <ion-navbar>
    <ion-title>
      Choose Location
    </ion-title>
    <ion-grid>
      <ion-row>
        <ion-col col-1>
          <ion-icon name="search"></ion-icon>
        </ion-col>
        <ion-col col-11>
          <input
            type="search"
            class="input text-input"
            [(ngModel)]="pickup"
            placeholder="Where from?"
            id="locationFrom2"
            (keyup)="searchLocationFrom()"
          />
        </ion-col>
      </ion-row>
    </ion-grid>
  </ion-navbar>
</ion-header>

<ion-content>
  <div #map id="map" (onClick)="onSetMarker($event)"></div>
  <ion-grid>
    <ion-row>
      <ion-col>
        <button ion-button block color="primary" (click)="onConfirm()">
          Confirm
        </button>
      </ion-col>
      <ion-col>
        <button ion-button block color="dark" (click)="onAbort()">
          Abort
        </button>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

在您的 .scss 文件中添加使用此代码。

    page-set-map {
  #map {
    width: 100%;
    height: 90%;
  }
  #description {
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
  }
  #infowindow-content .title {
    font-weight: bold;
  }
  #infowindow-content {
    display: none;
  }
  #map #infowindow-content {
    display: inline;
  }
  .pac-card {
    margin: 10px 10px 0 0;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    background-color: #fff;
    font-family: Roboto;
  }
  #pac-container {
    padding-bottom: 12px;
    margin-right: 12px;
  }
  .pac-controls {
    display: inline-block;
    padding: 5px 11px;
  }
  .pac-controls label {
    font-family: Roboto;
    font-size: 13px;
    font-weight: 300;
  }
  #pac-input {
    background-color: #fff;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    margin-left: 12px;
    padding: 0 11px 0 13px;
    text-overflow: ellipsis;
    width: 400px;
  }
  #pac-input:focus {
    border-color: #4d90fe;
  }
  #target {
    width: 345px;
  }
  .searchbar {
    position: absolute;
    top: 50px;
    left: 0;
    width: 100%;
    z-index: 10;
  }
  .searchbar .bar {
    width: 95%;
    margin: 0 auto;
  }
  .text-input {
    padding-left: 10px;
    padding-top: 9px;
    padding-bottom: 9px;
    margin: 0;
    background-color: #f9f9f9;
    box-shadow: 1px 3px 6px 1px #cccccc;
  }
  .text-input:focus {
    background-color: #ededed;
  }
  input {
    width: 100%;
    border-radius: 0 !important;
    padding: 10px;
  }
}

这些将设置您应用程序的前端。现在对于功能使用这个 .ts 文件(我已经为您的用例评论了一些项目,如果您需要地址功能或搜索功能,您也可以使用它们)

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams, Platform, ViewController, ToastController } from 'ionic-angular';
import { Location } from '../../app/models/location';
// import { Storage } from '@ionic/storage';

declare let google;
@Component({
  selector: 'page-set-map',
  templateUrl: 'set-map.html',
})
export class SetMapPage {
  pointer: any;
  @ViewChild('map') mapElement: ElementRef;
  map: any;
  location: Location;
  marker: Location;
  position;
  addressline: string;
  autocomplete: any;
  address;
  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    private platform: Platform,
    private viewCtrl: ViewController,
    private toastCtrl: ToastController
  ) {
    this.location = this.navParams.get('location');
  }


  ionViewDidLoad() {
    this.platform.ready().then(resp => {
      this.loadMap();
    })
    // let elem = <HTMLInputElement>document.getElementsByClassName('searchbar-input')[0];
    // this.autocomplete = new google.maps.places.Autocomplete(elem);
  }


  // getAddress(place: Object) {   
  //   this.address = place['formatted_address'];
  //   this.autocomplete=new google.maps.places.Autocomplete(this.address);
  //   google.maps.event.addListener(this.autocomplete, 'place_changed', () => {
  //     let place = this.autocomplete.getPlace();
  //     this.pointer.lat = place.geometry.location.lat();
  //     this.pointer.lng = place.geometry.location.lng();
  //     this.setLatLong(this.pointer.lat, this.pointer.lng, place);
  //   });
  // }

  // setLatLong(lat, lng, place){
  //   let latLng = new google.maps.LatLng(this.location.lat, this.location.lng);
  //   let mapOptions = {
  //     center: latLng,
  //     zoom: 15,
  //     mapTypeId: google.maps.MapTypeId.ROADMAP
  //   }
  //   this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
  // }

  searchLocationFrom() {
    let input = document.getElementById('locationFrom2');
    this.geoLocation(input).then(results => {
      this.map.panTo(results);
      // let latLng = new google.maps.LatLng(results.lat(),results.lng());

      // let mapOptions = {
      //   center: latLng,
      //   zoom: 15,
      //   mapTypeId: google.maps.MapTypeId.ROADMAP
      // }
      // this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
      // google.maps.event.addListener(this.map, 'click', (event) => {
      //   this.marker = new google.maps.Marker({ position: event.latLng, map: this.map });
      //   // console.log(event.latLng);   // Get latlong info as object.
      //   // console.log("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng()); // Get separate lat long.
      //   this.position = "" + event.latLng.lat() + "," + "" + event.latLng.lng();
      //   this.filterPosition();
      // });
    });
  }

  geoLocation(input) {
    return new Promise(function (resolve, reject) {
      let autocomplete = new google.maps.places.Autocomplete(input);
      google.maps.event.addListener(autocomplete, 'place_changed', function () {
        let place = autocomplete.getPlace();
        if (!place.geometry) {
          reject(place);
        }
        // resolve(place);
        resolve(place.geometry.location);
      });
    });
  }

  loadMap() {
    let latLng = new google.maps.LatLng(this.location.lat, this.location.lng);

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    google.maps.event.addListener(this.map, 'click', (event) => {
      this.marker = new google.maps.Marker({ position: event.latLng, map: this.map })
      this.position = "" + event.latLng.lat() + "," + "" + event.latLng.lng();
      this.filterPosition();
    });
  }
  filterPosition() {
    let str = this.position;
    let res = str.split(",");
    this.marker.lat = res[0];
    this.marker.lng = res[1];
    let geocoder = new google.maps.Geocoder;
    this.geocodeLatLng(geocoder, this.marker);
  }


  geocodeLatLng(geocoder, marker) {
    let latlng = { lat: parseFloat(marker.lat), lng: parseFloat(marker.lng) };
    geocoder.geocode({ 'location': latlng }, (results, status) => {
      if (status === 'OK') {
        if (results[0]) {
          let temp = results[0].formatted_address;
          this.addressline = temp;
        } else {
          window.alert('No results found');
        }
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }
    });
  }



  onConfirm() {
    if (this.addressline == null) {
      this.presentToast();
    } else {
      this.viewCtrl.dismiss({
        address: this.addressline
      });
    }
  }

  onAbort() {
    this.viewCtrl.dismiss();
  }
  presentToast() {
    let toast = this.toastCtrl.create({
      message: '\t\t Please select a position on map!',
      duration: 3000,
      position: 'top',
      cssClass: 'ErrorToast',
    });

    toast.present();
  }

  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);
    });

  }

  onSetMarker(event: any) {
    this.marker = new Location(event.coords.lat, event.coords.lng);
  }
}

谢谢。我希望这些资源可以满足很多请求。

关于angular - Ionic 在位置上或基于经度和纬度设置标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56091185/

相关文章:

angular - 如何在 Ionic 5 中获得 canGoBack 功能?

Angular 8.x e2e 测试无法运行

android - 如何通过蓝牙 (LE) 将图像传输到桌面应用程序

javascript - 使用无效数据调用 DocumentReference.set()。不支持的字段值 : undefined (found in field uid)

azure - 如何将 Ionic 3 (Angular 5) 应用程序连接到 Azure SQL 数据库?

javascript - ngClick 在 ngFor 内部

javascript - 如何从日期选择器 Angular Material 中读取日期

Angular 7 SELECT 选项在初始化时未选择

angular - 从图库图像中的 “share” 按钮将照片共享到我的 ionic 2 应用程序

javascript - Ionic V2 和 Cordova 插件 - 未捕获的类型错误 : Cannot set property 'test' of null