what add marker to map openlayer 5 with angular 6 - angular6

I'm using the OpenLayers 5 for my project in angular 6. I implemented it to show a map and it is working :-). But I can't make it show any markers, please help me!!! Show examples with this version OpenLayers...
import OlMap from 'ol/Map';
import OlXYZ from 'ol/source/XYZ';
import OlTileLayer from 'ol/layer/Tile';
import OlView from 'ol/View';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {fromLonLat} from 'ol/proj';
export class MyComponent implements OnInit {
map: OlMap;
source: OlXYZ;
layer: OlTileLayer;
view: OlView;
marker: Feature;
ngOnInit() {
this.marker = new Feature({
geometry: new Point([27.46164, 53.902257])
});
this.source = new OlXYZ({
url: 'http://tile.osm.org/{z}/{x}/{y}.png',
features: [this.marker]
});
this.layer = new OlTileLayer({
source: this.source
});
this.view = new OlView({
center: fromLonLat([27.56164, 53.902257]),
zoom: 14
});
this.map = new OlMap({
target: 'map',
layers: [this.layer],
view: this.view
});
}
}

You need a vector layer and a vector source to add features. Something like the following:
import Map from 'ol/Map';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import View from 'ol/View';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import XyzSource from 'ol/source/XYZ';
import TileLayer from 'ol/layer/Tile';
import { fromLonLat } from 'ol/proj';
export class MyComponent implements OnInit {
map: Map;
vectorSource: VectorSource;
vectorLayer: VectorLayer;
xyzSource: XyzSource;
tileLayer: TileLayer;
view: View;
marker: Feature;
ngOnInit() {
// Feature and vector
this.marker = new Feature({
geometry: new Point(fromLonLat([27.46164, 53.902257]))
});
this.vectorSource = new VectorSource({
features: [this.marker]
});
this.vectorLayer = new VectorLayer({
source: this.vectorSource
});
// XYZ
this.xyzSource = new XyzSource({
url: 'http://tile.osm.org/{z}/{x}/{y}.png'
});
this.tileLayer = new TileLayer({
source: this.xyzSource
});
// View and map
this.view = new View({
center: fromLonLat([27.56164, 53.902257]),
zoom: 14
});
this.map = new Map({
target: 'map',
layers: [this.tileLayer, this.vectorLayer],
view: this.view
});
}
}

Related

message error implementing google maps in ionic (touchstart,touchmove)

I use cordova geolocation and the google maps javascript api, and a simple implementation and still keep the error, when trying to zoom in or out.
the problem appears when I move and zoomed the map.
**
It is good to mention that this message appears when I connect the mobile for real time debugging with
ionic cordova run android -L
and exploring console messages with remote devices using chrome
chrome://inspect/#devices
<pre>
import { Component, OnInit, ElementRef, ViewChild } from '#angular/core';
import { Geolocation, Geoposition } from '#ionic-native/geolocation/ngx';
import { LoadingController, IonSlides } from '#ionic/angular';
declare var google: any;
#Component({
selector: 'app-mapa',
templateUrl: './mapa.page.html',
styleUrls:['./mapa.page.scss'],
})
export class MapaPage implements OnInit {
map: any;
marker: any;
#ViewChild(IonSlides, { static: true }) slide: IonSlides;
#ViewChild('map', { read: ElementRef, static: false }) mapRef: ElementRef;
constructor(
private geolocation: Geolocation,
private loadingCtrl: LoadingController
) { }
ngOnInit() { }
ionViewDidEnter() {
this.showMap();
}
async showMap() {
const loading = await this.loadingCtrl.create();
loading.present();
const myLatLng = await this.getLocation();
const options = {
center: myLatLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
this.map = new google.maps.Map(this.mapRef.nativeElement, options);
loading.dismiss();
}
</pre>

Mapbox missing Gl JS css

My map is not loading and no error is being displayed in the console.
please help.
this is the error screenshot as shown in the browser
there is no build error while compiling the code neither any error is thrown but the ma form mabox is not loading and is written as - Missing mapbox Gl JS CSS
the following is the code snippet for the same
// code for map.component.ts
import { Component, OnInit } from '#angular/core';
import * as mapboxgl from 'mapbox-gl';
import { MapService } from '../map.service';
import { GeoJson, FeatureCollection } from '../map';
#Component({
selector: 'app-map-box',
templateUrl: './map-box.component.html',
styleUrls: ['./map-box.component.css']
})
export class MapBoxComponent implements OnInit{
/// default settings
map: mapboxgl.Map;
style = 'mapbox://styles/kanavmalik10/cjfbjx6fp70fl2snuphc7zjw2';
lat = 37.75;
lng = -122.41;
message = 'Hello World!';
// data
source: any;
markers: any;
constructor(private mapService: MapService) {
}
ngOnInit() {
this.markers = this.mapService.getMarkers()
this.initializeMap()
}
private initializeMap() {
/// locate the user
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.map.flyTo({
center: [this.lng, this.lat]
})
});
}
this.buildMap()
}
buildMap() {
this.map = new mapboxgl.Map({
container: 'map',
style: this.style,
zoom: 13,
center: [this.lng, this.lat]
});
/// Add map controls
this.map.addControl(new mapboxgl.NavigationControl());
//// Add Marker on Click
this.map.on('click', (event) => {
const coordinates = [event.lngLat.lng, event.lngLat.lat]
const newMarker = new GeoJson(coordinates, { message: this.message })
this.mapService.createMarker(newMarker)
})
/// Add realtime firebase data on map load
this.map.on('load', (event) => {
/// register source
this.map.addSource('firebase', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: []
}
});
/// get source
this.source = this.map.getSource('firebase')
/// subscribe to realtime database and set data source
this.markers.subscribe(markers => {
let data = new FeatureCollection(markers)
this.source.setData(data)
})
/// create map layers with realtime data
this.map.addLayer({
id: 'firebase',
source: 'firebase',
type: 'symbol',
layout: {
'text-field': '{message}',
'text-size': 24,
'text-transform': 'uppercase',
'icon-image': 'rocket-15',
'text-offset': [0, 1.5]
},
paint: {
'text-color': '#f16624',
'text-halo-color': '#fff',
'text-halo-width': 2
}
})
})
}
/// Helpers
removeMarker(marker) {
this.mapService.removeMarker(marker.$key)
}
flyTo(data: GeoJson) {
this.map.flyTo({
center: data.geometry.coordinates
})
}
}
<input type="text" [(ngModel)]="message" placeholder="your message...">
<h1>Markers</h1>
<div *ngFor="let marker of markers | async">
<button (click)="flyTo(marker)">{{ marker.properties.message }}</button>
<button (click)="removeMarker(marker)">Delete</button>
</div>
<div class="map" id="map"></div>
You seed to include the GL JS CSS stylesheet. See the quickstart at https://docs.mapbox.com/mapbox-gl-js/overview/#quickstart
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />

Ionic 2 Google Maps:: Uncaught (in promise): TypeError: Cannot read property 'firstChild' of null

I'm using ionic 2 and trying to load google map using its JS API.
Here is my code:
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, Platform, NavParams } from 'ionic-angular';
declare var google;
#Component({
selector: 'page-map',
templateUrl: 'map.html',
})
export class MapPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
latitude : any;
longitude : any;
constructor(public platform: Platform, public navCtrl: NavController,public navParams: NavParams) {
this.platform = platform;
this.initializeMap();
}
ionViewDidLoad(){
this.initializeMap();
}
initializeMap() {
this.platform.ready().then(() => {
var minZoomLevel = 12;
this.map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var position = new google.maps.LatLng("23.032612699999998", "72.56187790000001");
var dogwalkMarker = new google.maps.Marker({position: position, title: "Testing"});
dogwalkMarker.setMap(this.map);
});
}
}
I have also added reference of the JS in my index.html file before cordova.js:
<script src="http://maps.google.com/maps/api/js"></script>
Here is my html:
<ion-header>
<ion-navbar hideBackButton side="left">
<ion-title style="margin-left: 0px;"><span class="menuTitle">Map</span></ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map"></div>
</ion-content>
The code does not display any error but when I try to load this page it displays error like:
Uncaught (in promise): TypeError: Cannot read property 'firstChild' of null
Use mapElement
Typescript file
let minZoomLevel = 12;
let mapOptions = {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

Ionic 2/3 Google Maps Keeps Adding Marker

I have an Ionic 3 app, using Google Maps. On load I am rendering a map with a Marker on the current user's location.
I am using watchPostion to update the marker when the user's position changes.
However, the marker keeps being set, even if the position does not change, it is added on top.
Also, when the position does change, the marker does not move, rather a new one is added, so I end up with a trail of markers.
I'd like to only add the maker if the position has changed and either remove / add the marker if it does, or simply have it's position updated.
This is my Ionic Component / Page -
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { MapStyle } from './map-style';
declare var google;
#Component({
selector: 'home-page',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map: any;
constructor(
public navCtrl: NavController,
public geolocation: Geolocation
) { }
ionViewDidEnter() {
this.initializeMap();
}
private initializeMap() {
const mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
styles: [...MapStyle]
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.geolocation.watchPosition()
.subscribe((position) => {
const geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
const currentUserMarker = new google.maps.Marker({
map: this.map,
position: geolocate,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: "#2a929f",
fillOpacity: 0.4,
strokeWeight: 0.4
}
// content: `${position.coords.latitude} <br /> ${position.coords.longitude}`
});
this.map.panTo(geolocate);
currentUserMarker.setPosition(geolocate);
}, (err) => this.handleError)
}
private handleError(err) {
console.log(err);
}
}
Rookie mistake.
Every time watchPosition was called I created a new instance of the marker.
Declared marker higher in the scope and then wrapped my logic in an if / else.
if (this.marker != null) {
this.marker.setPosition(geolocate);
this.map.panTo(geolocate);
} else {
this.marker = new google.maps.Marker({
position: geolocate,
map: this.map,
............

Ionic2 google maps image layer

I am building an Ionic2 app where I am using google maps as an orientation map and I need to put an image layer on top of the map. I am trying to put building layout image over the building complex in Google maps.
I found this solution for javascript here, which is exactly what I need: Google maps js API
I am quite new to Ionic2 and Anglular2 and having no luck figuring it out so far.
Any advice appreciated
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: 'map',
templateUrl: 'map.html'
})
export class MapPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
lat : any ;
lng : any ;
constructor(public navCtrl: NavController, public geolocation: Geolocation) {
this.getGeoLocation();
}
initializeMap() {
var minZoomLevel = 17;
let mapOptions =
{
zoom: minZoomLevel,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
getGeoLocation(){
this.geolocation.getCurrentPosition().then((position) => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.initializeMap();
}, (err) => {
console.log(err);
});
}
Well, apparently it was easier than I thought. You just define image boundaries and create an instance of an overlay and then add it to the map like this...
var oldBuilding = {
north: 53.27959,
west: -9.01287,
south: 53.278038,
east: -9.00876
};
this.oldBuildingOverLay = new google.maps.GroundOverlay('../assets/Map.png', oldBuilding);
this.oldBuildingOverLay.setMap(this.map);
Declare oldBuildingOverlay: any; and you're up and running.