我正在开发我的第一个有角度的Web应用程序,我想介绍类似于Google地图的内容。由于新的计费政策,我不想使用最后一个,所以我尝试了MapBox。
在学习完本教程之后,我设法创建了所需的地图;问题是,我不知道如何在角度组件上显示它。
我为地图生成了该文件,并且可以与浏览器完美结合,并且可以将其直接粘贴到我的角度项目的index.html上。但是当我尝试在组件上使用它时,我不知道该怎么做。
geom_label
我将<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Points on a map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'myToken'; // replace this with your access token
var map = new mapboxgl.Map({
container: 'map',
style: 'my style URL', // replace this with your style URL
center: [-2.8662684, 43.2806562],
zoom: 15
});
// code from the next step will go here
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['rhynux'] // replace this with the name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
var popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.title + '</h3><p>' + feature.properties.description + '</p>')
.setLngLat(feature.geometry.coordinates)
.addTo(map);
});
</script>
</body>
</html>
移到了组件上;但是会引发错误“找不到地图容器”。
我还尝试安装一些this one之类的nom程序包,但是它没有足够的信息说明如何将其用于像我这样的新手。
This another one也没有文档...
我查看了几篇SO帖子,但对如何执行却一无所知。
谢谢。非常感谢您的帮助
答案 0 :(得分:2)
我遇到了同样的问题,并通过使用@ViewChild来定位地图元素来解决了该问题。这是一个基本的Angular组件,将显示一个Mapbox地图。
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import mapboxgl from 'mapbox-gl';
@Component({
selector: 'app-map',
template: '<div #mapElement style="height:200px"></div>'
})
export class MapComponent implements OnInit {
map: mapboxgl.Map;
@ViewChild('mapElement') mapElement: ElementRef;
constructor() { }
ngOnInit() {
mapboxgl.accessToken = 'ACCESS_TOKEN_HERE';
}
ngAfterViewInit(){
this.map = new mapboxgl.Map({
container: this.mapElement.nativeElement,
style: 'mapbox://styles/mapbox/streets-v9'
});
}
}
答案 1 :(得分:2)
我遇到了这个问题,所以我只在方法中添加了setTimeOut
:
Oninit(){
setTimeout(() => {
let mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=<key>', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'your.mapbox.access.token'
}).addTo(mymap);
}, 100);
}