Tuesday, December 17, 2019

Google Maps Integration on Ionic 4

Posted by Web Idea Solution | December 17, 2019 Categories: , ,
 
Google Maps Integration on Ionic 4
Google Maps integration is consistently one of the most popular features of mobile applications.

Add Goolge Maps API in Ionic 4

Google Maps JavaScript API can be used in web applications, but now it needs an API key to use it. To know more on how to get API Key visit this link. Now open index.html at the root of your Ionic Application, then add the following script with your key in head section.
<script src="https://maps.google.com/maps/api/js?key=AIzaSyA20kmNoWwu5uwtX4lrpb2c7D3WTEIJIBQ"></script>

Geo location 

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

Home Component html

The homepage is the root page of your application. change the homepage content like following.
<ion-content fullscreen>
    <div class="location-col">
        <div class="google-map">
            <div #mapElement id="map"></div>
        </div>
    </div>
</ion-content>


Home Component TS

Now we will modify home component file to load Google maps. Replace following code in home.page.ts file.
import { Geolocation } from '@ionic-native/geolocation/ngx';
declare var google;
@ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
loadMap() {
    this.geolocation.getCurrentPosition().then((resp) => {
      let latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      this.getAddressFromCoords(resp.coords.latitude, resp.coords.longitude);
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
      this.map.addListener('tilesloaded', () => {
        console.log('accuracy',this.map);
        this.getAddressFromCoords(this.map.center.lat(), this.map.center.lng())
      });
    }).catch((error) => {
      console.log('Error getting location', error);
    });
 }



Home Component CSS

#map {
  width: 100%;
  height: 70vh;
}
 
 
For further details, Contact us:



Email: info@webideasole.com

Ph: +91 99325 55605  

0 comments:

Post a Comment

  • Facebook
  • Twitter
  • Linkedin
  • Pinterest
  • Email