位置或基于经度和纬度的离子设置标记 [英] Ionic set marker on location or based on longitude and latitude

查看:54
本文介绍了位置或基于经度和纬度的离子设置标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm following some tutorial i want to set the marker on current location. I'm taking longitude and latitude values of user, and I need to show a marker on current location or possible by longitude and latitude values. And one more question can i show the address of that location on map? In some answers i check there are only option of set marker on center is there any option to set marker on current location?

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

还有另一件事需要显示该经度和纬度值的地址.

And one more thing also need to show the address of that longitude and latitude value.

推荐答案

嘿,我正在分享Maps的完整实现-latLng和Markers.

Hey I'm Sharing complete implementation of Maps - latLng and Markers.

在您的HTML文件中.

In Your HTML File.

<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文件中添加使用此代码.

In your .scss file add use this code.

    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文件(我已经为您的用例注释了一些项目,如果您需要地址功能或搜索功能,也可以使用它们)

These will set the Front-End of your App. Now for functionality use this .ts file (I have commented some items for you use case you can use them too if you need address functionality or search functionality)

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

谢谢.我希望这些资源可以满足很多要求.

Thanks. I hope these resources can serve a lot of requests.

这篇关于位置或基于经度和纬度的离子设置标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆