Making Google Maps using Angular Component @angular/google-maps
making simple google maps component with just few lines of code in minutes
Hello my name is anno im a software engineer. here to show my components @angular/google-maps that i’ve been made
the new angular component has been release , ie : @angular/google-maps
visit link here to know more https://github.com/angular/components/releases/tag/9.0.0-rc.0
MY GOOGLE MAPS COMPONENT
In this google-maps i’m gonna implements some Function :
- Showing Maps
- Setting Marker
- Getting Product Location based on latitude and longtitude
- Getting User Location
- Calculate Distance product location with user location in Kilometer
in the end my google maps component will look like this :
Setup your Angular for google maps
npm install @angular/google-maps
when installation is finished, we must add the Angular module GoogleMapsModule to the import declaration
import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { GoogleMapsModule } from '@angular/google-maps'
import { AppComponent } from './app.component'
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, GoogleMapsModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
please note bold text that’s what you should import
Place your api key at index.html inside head
<script src=”https://maps.googleapis.com/maps/api/js?key=YOUR API KEY"></script>
Now we are ready to have fun with google maps component.
please dont follow up my layout code blindly
place this inside your component html #mapcontainer will be used in TS Component with view child to accessing DOM
<div class="container-maps"> <div class="container-maps-one">
<!-- HERES MY ASSETS DONT FOLLOW UP BLINDLY. Go search for another assets -->
<p class="maps-text-location"><img src="assets/images/location.png"><span class="location-margin">{{listingPlace}}</span></p>
<p class="maps-text-location">{{distanceProductToUser ? distanceProductToUser : '-'}} km from you</p>
</div><div style="margin-top: 12px;">
<div #mapContainer id="map"></div>
</div>
</div>
place this inside your css for determine your size of maps
.container-maps {
display: flex;
margin-top: 25.9px;
flex-direction: column;
width: 65%; margin-right: 25px;}.container-maps-one {
display: flex;
flex-direction: row;
justify-content: space-between;
}.maps-text-location {
font-family: Roboto-med;
font-size: 14px;
font-weight: 500;
font-stretch: normal;
font-style: normal;
line-height: 1.29;
letter-spacing: normal;
text-align: center;
color: #b0b0b0;
}#map {height: 139px;width: 100%;}
after doing code for layout let accessing our html element on TS using this code .
// Accessing HTML Element
@ViewChild('mapContainer', { static: false }) gmap: ElementRef; productLat; productLong; userLat; userLong;
map: google.maps.Map;
listingPlace; distanceProductToUser;ngOnInit(){
// showing map this.mapInitializer();
// get our location this.getLocation(); //calculate our location distance to product this.calculateDistanceUserToProduct(); }// ANGULAR ON AFTER VIEW LIFECYCLE WILL BE CALLED AFTER OUR LAYOUT DONE RENDERING
ngAfterViewInit() { this.mapInitializer(); this.getLocation(); this.calculateDistanceUserToProduct(); }
function for mapInitializer(); in this function we gonna set our marker map and our map style after that we gonna fetch our address using function GeoReverse
mapInitializer() {// place your product lat or longtitude here
this.productLat = 40.785091; // change it to your preferences this.productLong = 73.968285; // <-- static const coordinates = new google.maps.LatLng(this.productLat, this.productLong); // init our coordinate for marker :)this.marker = new google.maps.Marker({ position: coordinates, map: this.map })// check here to get to know about map options docs const mapOptions: google.maps.MapOptions = {
// here to place centering our location based on coordinates center: coordinates, zoom: 16, fullscreenControl: false, mapTypeControl: false, streetViewControl: false };//set our lovely google maps here and marker here
this.map = new google.maps.Map(this.gmap.nativeElement, mapOptions); this.marker.setMap(this.map); // get address name based on latitude and longtitude // here we do Reverse Geocoding technique that convert Latitude and // longtitude to be lovely human readable information like address
this.getProductAddressMap().subscribe((data: any) => { this.listingPlace = // doing traverse from json response that we get from //getProductAddressMap() below
data.results[1].address_components[0].short_name; })
}
function getProductAddressMap() this function need 2 input that is lat and long to get address
getProductAddressMap() {var addressName = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${this.productLat},${this.productLong}&key=YOUR_API_KEY`;return this.http.get(addressName);}
function getUserLocation() this function will ask user to allow our web to access their location by little notif pop up for first time and next time user will automatically allowed our web to access their location without do anything
navigator.geolocation.getCurrentPosition((position) => { this.userLat = position.coords.latitude; this.userLong = position.coords.longitude; this.calculateDistanceUserToProduct(); }, error => { alert(“Please Allow Google Maps in your Browser”); })
function calculateUserDistancetoProduct this function is used for calculating user current location to the product seller and let’s do some math magic here that formula i get from stackoverflow
calculateDistanceUserToProduct() { var earthRadius = 6371 // Radius of the earth in km
t var dLat = this.deg2rad(this.productLat — this.userLat); var dLon = this.deg2rad(this.productLong — this.userLong);var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +Math.cos(this.deg2rad(this.userLat)) * Math.cos(this.deg2rad(this.productLat)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 — a)); var dist = earthRadius * c; // Distance in km var finalDist = dist.toFixed(2); if(finalDist == ‘NaN’){ this.distanceProductToUser = null; }else{ this.distanceProductToUser = finalDist; } console.log(“final dist”,this.distanceProductToUser); }deg2rad(deg) { return deg * (Math.PI / 180) }
this post is made by purpose to sharing my code and looking for room of improvement , ready and want to be criticized , if you have your amazing google maps component don’t hesitate to share on the comment below!
References :
get your API key here link
see google maps api to build more advance maps link
see expert post link
see good medium angular deep dive article https://medium.com/angular-in-depth