создание простого компонента карт Google с помощью всего нескольких строк кода за считанные минуты
Здравствуйте, меня зовут Анно, я инженер-программист. здесь, чтобы показать мои компоненты @ angular / google-maps, которые я сделал
выпущен новый компонент angular, то есть: @ angular / google-maps
перейдите по ссылке, чтобы узнать больше https://github.com/angular/components/releases/tag/9.0.0-rc.0
КОМПОНЕНТ МОЙ GOOGLE КАРТЫ
В этих картах Google я собираюсь реализовать некоторую функцию:
- Отображение карт
- Установка маркера
- Получение местоположения продукта на основе широты и долготы
- Получение местоположения пользователя
- Вычислить расстояние до местоположения продукта с местоположением пользователя в километрах
в итоге мой компонент карт Google будет выглядеть так:
Настройте свой Angular для карт Google
npm install @angular/google-maps
когда установка будет завершена, мы должны добавить модуль Angular GoogleMapsModule в декларацию импорта
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 {}
обратите внимание на жирный текст, который вы должны импортировать
Поместите свой ключ api в index.html внутри головы
<script src=”https://maps.googleapis.com/maps/api/js?key=YOUR API KEY"></script>
Теперь мы готовы развлечься с компонентом Google Maps.
Пожалуйста, не следите вслепую за моим кодом макета
поместите это в свой компонент html #mapcontainer будет использоваться в компоненте TS с дочерним представлением для доступа к 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>
поместите это в свой CSS, чтобы определить размер карт
.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%;}
после выполнения кода для макета разрешите доступ к нашему элементу html в TS с помощью этого кода.
// 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(); }
функция для mapInitializer (); в этой функции мы установим нашу карту маркеров и наш стиль карты, после этого мы извлечем наш адрес с помощью функции 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 () этой функции требуется 2 ввода, широта и долгота, чтобы получить адрес
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 () эта функция попросит пользователя разрешить нашему Интернету доступ к их местоположению с помощью небольшого всплывающего уведомления в первый раз, и в следующий раз пользователь автоматически разрешит нашему Интернету доступ к их местоположению без каких-либо действий
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 эта функция используется для вычисления текущего местоположения пользователя до продавца продукта, и давайте сделаем здесь некоторую математическую магию, которую я получаю из 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) }
Этот пост сделан с целью поделиться своим кодом и найти возможности для улучшения, готов и хочет, чтобы вас критиковали, если у вас есть замечательный компонент Google Maps, не стесняйтесь поделиться в комментариях ниже!
Использованная литература :
получите ключ API здесь ссылка
см. API карт Google для создания дополнительных карт ссылка
см. сообщение эксперта ссылка
см. статью о хороших среднеугловых глубоких погружениях https://medium.com/angular-in-depth