Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic set marker on location or based on longitude and latitude

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.

like image 596
Umaiz Khan Avatar asked May 11 '19 14:05

Umaiz Khan


People also ask

How do you mark GPS coordinates?

Enter Coordinates on Android If you copy the coordinates from another spot, you can easily paste them into Google Maps. But of course, you can type them too. Open Google Maps, enter the coordinates into the Search box at the top, and hit the Search key on the keyboard. You'll see a pin appear on the map for the spot.


1 Answers

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

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>

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

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.

like image 178
Sami Haroon Avatar answered Oct 11 '22 07:10

Sami Haroon