Incorporating javascript maps into Angular - javascript

I am trying to incorporate Javascript google maps into my Angular 8 project in order to add more functionality than AGM. I have created a typings.d.ts file and included my javascript in the angular.json but i am still getting the error: 'map' is declared but its value is never read. Here is my code...
component.html
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key={{apiKey}}&callback=initMap"
async defer>
</script>
<script >
</script>
</body>
</html>
component.ts
import * as map from 'map';
import { Component, OnInit } from '#angular/core';
import { environment } from '../../environments/environment';
#Component({
selector: 'app-google-maps',
templateUrl: './google-maps.component.html',
styleUrls: ['./google-maps.component.css']
})
export class GoogleMapsComponent implements OnInit {
private apiKey = environment.googleMapsAPIkey;
constructor() { }
ngOnInit() {
}
}
maps.js
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
typings.d.ts
declare module Map {
export interface Main {
map;
}
}
declare var Map:Map.Main;

Following code displated google maps in developer mode.
html
<div style="width: 1000px;height: 300px;" id="map"></div>
component.ts
constructor() {
var dynamicScripts = ["https://maps.googleapis.com/maps/api/js?key="apiKey"];
for (var i = 0; i < dynamicScripts.length; i++) {
let node = document.createElement('script');
node.src = dynamicScripts [i];
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
}
ngOnInit() {
setTimeout(()=>{ //
this.initMap();
},2000);
}
Note Instead of setTimeout we can use promies.then().

Related

Is it possible to call Google Maps Javascript API from JS function and display it on ion-content?

I have created my an Google Maps API snippet of code that displays a map in a box:
var map;
function initMap() {
var mapCenter = {
lat: 50,
lng: 50
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: mapCenter,
disableDefaultUI: true
});
map.setOptions({
minZoom: 5,
maxZoom: 20
});
};
<!DOCTYPE html>
<html>
<style>
.box {
width: 300px;
height: 300px;
border: 5px solid;
margin: auto;
}
}
</style>
<head>
</head>
<body>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API-KEY&callback=initMap">
</script>
<div class="box" id="map">
</div>
</body>
</html>
Now, I would like to add this map in an ion-content that is included in the following:
LoginModal = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({
selector: 'page-login-modal',template:
'<ion-header class="{{customClasses}}">
<ion-toolbar>
<ion-title>{{ title | translate }}
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="{{customClasses}}">
<div class="box" id="map">
</div>
</ion-content>'
}),], LoginModal);
return LoginModal;
}());
For this reason I have created a JS function (in the same file as the ion-content) in order to make the Google Maps API call and pass my arguments:
var map;
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap";
LoginModal.prototype.initMap = function () {
var mapCenter = {
lat: 50,
lng: 50
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: mapCenter,
disableDefaultUI: true
});
map.setOptions({
minZoom: 5,
maxZoom: 20
});
};
The above code does not display the map but instead only the box. I have tried to place the "src="https:" line in the index.html file (in the body and in the head), but again only the box is displayed.
In order to test that my JS functions can alter the ion-context, I have created another function (next to initMap()) that was able to replace a photo with text upon pressing a button.
What change should I do in order to make it display the map (since I can make it happen in the JS snippet example above)?
I have done this, try replicating it in your code and at last you need to call createMap().
Here is one app available, you can take a reference from it but it is for Bing
https://github.com/microsoft/Bing-Maps-Fleet-Tracker/tree/master/MobileClient
private loadPromise: Promise<void>;
private load(): Promise < void > {
if (this.loadPromise) {
return this.loadPromise;
}
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
const mapsCallback = 'initMap';
script.src = `https://maps.googleapis.com/maps/api/js?key=<GOOGLE-MAP-KEY>&callback=initMap`;
this.loadPromise = new Promise <
void >
((resolve: Function, reject: Function) => {
window[mapsCallback] = () => {
this.loadLableMarker().then(() => {
resolve();
});
};
script.onerror = (error: Event) => {
console.error('maps script error' + error);
reject(error);
};
});
document.body.appendChild(script);
return this.loadPromise;
}
createMap(element: HTMLElement, options): Promise {
return this.load().then(() => {
return new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: mapCenter,
disableDefaultUI: true
});
});
}

How to implement Google Map JavaScript in Angular2+?

I am trying to implement Google Map in my Angular6 component. However, I am unable to do so. I have embedded Google Map JavaScript from -
https://developers.google.com/maps/documentation/javascript/examples/rectangle-simple
My map doesn't load.
app.component.html
<div id="map"></div>
app.component.ts
import { Component, OnInit,AfterViewInit } from '#angular/core';
import { ViewChild, ElementRef, Renderer } from '#angular/core'
const url = '../../../assets/googlemap.js'
#Component({
selector: 'app-search-api',
templateUrl: './search-api.component.html',
styleUrls: ['./search-api.component.scss']
})
export class SearchApiComponent implements OnInit, AfterViewInit {
PhotoGoogleSDK: any;
constructor() { }
ngOnInit() {
this.loadScript();
}
// ------------------ Javascript code ----------------
public loadScript() {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
googlemap.js
var citymap = {
chicago: {
center: {lat: 41.878, lng: -87.629},
population: 2714856
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 4,
center: {lat: 37.090, lng: -95.712},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
}
}
var tag = document.createElement('script');
tag.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCXNFDDBMRr6YX8LJtltvEbQJsLA&callback=initMap";
tag.defer = true;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
In order to implement google maps in angular2+ you have to do these things.
Insert the google map script in your index.html file. (You need to get a API key from Google.)
Now in your component.ts declare const google as any
declare const google: any;
Now in your html of your component, add new div with an id
<div id="google_map" class="map"></div>
Include this method and run it when initialize (add method to ngOnInit())
public initializeMap() {
let _map = document.getElementById('google_map');
let lat = YOUR_INITIAL_LATITUDE;
let lng = YOUR_INITIAL_LONGITUDE;
let pos = new google.maps.LatLng(lat, lng);
let map = new google.maps.Map(_map, {
center: pos,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
}
Note that you may need to install google typing.
npm install --save #types/googlemaps

Draw Polyline between markers Ionic Google Maps JavaScript

Hi guys this is my first post in this site, im working in a App in Ionic that shows your position with a marker when you push a button, you can push it again to update your position and add a Marker on that position, i want to draw a Polyline between this markers but i havent succeed yet. i know there are some ways to draw polylines my idea is to extract the lat, long coordinates of the marker, save them in a array and then set that as a "path" to draw the Polyline but im having problems with the creation of the array like in the comment below. here is my code:
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController} from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
declare var google;
#Component({
selector: 'home-page',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map: any;
me: any;
markers=[];
lat=[];
long=[];
constructor(public navCtrl: NavController, public geolocation: Geolocation) {
}
ionViewDidLoad(){
this.loadMap();
}
loadMap() {
this.geolocation.getCurrentPosition().then((position) => {
let mylatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: mylatLng,
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,
animation: google.maps.Animation.DROP,
});
let content = '<p>PosiciĆ³n: ' + marker.setPosition() + '</p>'
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
marker.setPosition(me);
},
function(error) {
// ...
});
this.markers.push(marker);
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
infoWindow.setContent('<p>PosiciĆ³n: ' + me + '</p>')
},
function(error) {
// ...
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
setMapAll(map) {
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(map);
}
}
clearMarkers() {
this.setMapAll(null);
}
deleteMarkers() {
this.clearMarkers();
this.markers = [];
}
// Im having problems here
addPolyLine() {
var poly = new Array();
for (var j=0; j<this.lat.length;j++){
var pos= new google.maps.LatLng(this.lat[j],this.long[j])
poly.push(pos);
}
var flightPath = new google.maps.Polyline({
path: poly,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(this.map);
}
}
And the HTML page:
<ion-header>
<ion-navbar>
<ion-title>
MapaPrueba
</ion-title>
<ion-buttons end>
<button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Agregar Pos</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map"></div>
<ion-fab left bottom>
<button ion-fab color="light" (click)="clearMarkers()">
<ion-icon name="eye-off"></ion-icon>
</button>
</ion-fab>
</ion-content>
There is a full example of that in the official documentation and here below as well.
In short you have to:
Create a Polyline and set it on the map (one time)
Get the Polyline path with the Polyline getPath() method
Push your new
coordinates to the path
var map;
var polyLine;
var polyOptions;
function initialize() {
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0,0)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
polyOptions = {
strokeColor: '#0026b3',
strokeOpacity: 1.0,
strokeWeight: 1,
geodesic: true,
}
polyLine = new google.maps.Polyline(polyOptions);
polyLine.setMap(map);
google.maps.event.addListener(map, 'click', function(event) {
addPoint(event);
});
}
function addPoint(event) {
var path = polyLine.getPath();
path.push(event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
});
map.setCenter(event.latLng);
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

Load Google Maps JS API in component [Angular]

How is it possible to load an external js file, from a url in an Angular component?
To be specific, I'm trying to load google-maps-api to my angular project. Currently, I'm doing it in my index.html like this:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
Note: I'm aware of angular-maps. That's not an option.
You can use Promise to load google API asynchronously whenever you want.
// map-loader.service.ts
import ...
declare var window: any;
#Injectable()
export class MapLoader {
private static promise;
map: google.maps.Map;
public static load() {
if (!MapLoader.promise) { // load once
MapLoader.promise = new Promise((resolve) => {
window['__onGapiLoaded'] = (ev) => {
console.log('gapi loaded')
resolve(window.gapi);
}
console.log('loading..')
const node = document.createElement('script');
node.src = 'https://maps.googleapis.com/maps/api/js?key=<YOUR _API_KEY>&callback=__onGapiLoaded';
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
return MapLoader.promise;
}
initMap(gmapElement, lat, lng) {
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: 12
});
});
}
}
Component
//maps.component.ts
...
#Component({
selector: 'maps-page',
templateUrl: './maps.component.html'
})
export class MapsComponent implements OnInit {
#ViewChild('gmap') gmapElement: any;
constructor(public mapLoader: MapLoader) { }
ngOnInit() {
this.mapLoader.initMap(this.gmapElement, -37.81, 144.96) // await until gapi load
}
...
}
Component HTML
// maps.component.html
<div #gmap ></div>
Don't forget to add CSS to the element.
A solution is to create the script tag dynamically in ngAfterViewInit()
import { DOCUMENT } from '#angular/common';
...
constructor(private #Inject(DOCUMENT) document,
private elementRef:ElementRef) {};
ngAfterViewInit() {
var s = this.document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.googleapis.com/maps/api/js?key=API_KEY";
this.elementRef.nativeElement.appendChild(s);
}
See also https://github.com/angular/angular/issues/4903
Update
<div id="map" #mapRef></div>
export class GoogleComponent implements OnInit {
#ViewChild("mapRef") mapRef: ElementRef;
constructor() { }
ngOnInit() {
this.showMap();
}
showMap() {
console.log(this.mapRef.nativeElement);
const location = { lat: 28.5355, lng: 77.3910 };
var options = {
center: location,
zoom: 8
}
const map = new google.maps.Map(this.mapRef.nativeElement, options);
this.addMarket(map, location);
}
addMarket(pos, map) {
return new google.maps.Marker({
position: pos,
map: map,
});
}
}

Initializing Markers and Infowindow in Ionic Google Maps

once again I have met my nemesis, adding google markers and setting content within and info-window. In this code, I have already completed a geolocation, and from my current location I, would like to perform a search on nearby places. The places I search will be retrieved from an Ionic list page I have already implemented. From what ever I choose on the list ex. Fire Stations, I would want my code to perform a Places Search, and the results turn up on my map as markers, with infowindow content from google libraries. My problem is that the markers are not on my map, and you can probably guess, that means no info window. If you could provide me with some direction. I am preforming this in Ionic.
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DirectionPage} from '../direction/direction';
/**
* Generated class for the PlacesPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
declare var google;
this.marker = [];
#Component({
selector: 'page-places',
templateUrl: 'places.html',
})
export class PlacesPage {
places: Array<any>;
map: any;
currentLocation: any;
latitude: Number;
longitude: Number;
keyword: String;
searchType: String;
distance: Number;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.latitude = navParams.get('latitude');
this.longitude = navParams.get('longitude');
this.keyword = navParams.get('keyword');
this.searchType = navParams.get('type');
this.distance = navParams.get('distance');
}
ionViewDidLoad() {
this.queryPlaces().then((results : Array<any>)=>{
for (let i=0; i < results.length; i++){
this.createMarker(results[i]);
}
this.places = results;
}, (status)=>console.log(status));
}
queryPlaces(){
this.currentLocation = new google.maps.LatLng(this.latitude,this.longitude);
let mapOptions = {
zoom: 10,
center: this.currentLocation,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById("map"), mapOptions);
let service = new google.maps.places.PlacesService("service");
let request = {
location : this.currentLocation,
radius: this.distance,
types: [this.searchType],
rankBy: google.maps.places.DISTANCE
};
return new Promise((resolve,reject)=>{
service.nearbySearch(request, function(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK){
resolve(results);
}else{
reject(results);
}
});
});
}
createMarker(place){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: place.geometry.location,
title: place.name,
});
google.maps.event.addListener(marker, 'click', function(){
let infowindow = new google.maps.infowindow({
content : this.place
});
infowindow.open(this.map,marker);
});
}
goToDirectionPage(index){
}
}
I realized the "I" in infowindow needed to be capitalized. Also, place.geometry.location gets the position for the marker object.
createMarker(place){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: place.geometry.location,
title: place.name,
});
google.maps.event.addListener(marker, 'click', function(){
let infowindow = new google.maps.InfoWindow({
content: place.name
});
infowindow.open(this.map,marker);
})

Categories

Resources