在地图上添加GeoJSON作为标记

时间:2018-09-25 08:18:05

标签: mapbox mapbox-marker

我的目标很简单,但是我很难实现它。我尝试了不同的方法,尝试了许多例子,但每次都失败了。

我需要什么:一个带有标记的简单地图,该标记是我通过GeoJSON文件提供的。

我一直在尝试:

  • 将GeoJSON作为Tileset导入到Mapbox中(无法设置自定义图标,因此看起来只有点的外观很难看)

  • 在本地加载GeoJSON并分别显示为标记(无效)

        var showInfoDialog = false;
		mapboxgl.accessToken = 'pk.eyJ1IjoicnNiYXVtYW5uIiwiYSI6IjdiOWEzZGIyMGNkOGY3NWQ4ZTBhN2Y5ZGU2Mzg2NDY2In0.jycgv7qwF8MMIWt4cT0RaQ';
		var map = new mapboxgl.Map({
			container: 'map',
			style: 'mapbox://styles/mapbox/dark-v9',
			center: [-74.0059, 40.7128],
			zoom: 15.5,
            pitch: 45,
            minZoom: 9,
            maxZoom: 18,
			bearing: -25.0,
           
		});
        
            
        
        map.once('style.load', function(e) {
            
            // Insert the layer beneath any symbol layer.
            var layers = map.getStyle().layers;

            var labelLayerId;
            for (var i = 0; i < layers.length; i++) {
                if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
                    labelLayerId = layers[i].id;
                    break;
                }
            }
            
            map.addControl(new mapboxgl.GeolocateControl({
                positionOptions: {
                    enableHighAccuracy: true
                },
                trackUserLocation: true
            }));            

            if (window.location.search.indexOf('embed') !== -1) map.scrollZoom.disable();
            
            map.addSource('geojson', {
                type: 'geojson',
                data: 'https:/xxxxx.json'
            });
              /*
             // add markers to map
            map.getSource('geojson').forEach(function(marker) {
                // create a DOM element for the marker
                var el = document.createElement('div');
                el.className = 'marker';
                el.style.backgroundImage = 'url(https://map.gogames.live/images/arena.png';
                el.style.width = marker.properties.iconSize[0] + 'px';
                el.style.height = marker.properties.iconSize[1] + 'px';

                el.addEventListener('click', function() {
                    window.alert(marker.properties.name);
                });

                // add marker to map
                new mapboxgl.Marker(el)
                    .setLngLat(marker.geometry.coordinates)
                    .addTo(map);
            });
            */
            
            
            //Hide loading bar once tiles from geojson are loaded
            map.on('data', function(e) {
                if (e.dataType === 'source' && e.sourceId === 'arenen') {
                    document.getElementById("loader").style.visibility = "hidden";
                }
            });
        });
body {
  margin: 0;
  padding: 0;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

.map-overlay {
  position: absolute;
  width: 180px;
  top: 0;
  left: 10px;
  padding: 10px;
  margin-left: 5px;
  margin-top: 2px;
  margin-bottom: 2px;
  margin-right: 5px;
  z-index: 1;
}

.map-overlay .map-overlay-inner {
  background: rgba(0, 0, 0, .8);
  color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.10);
  border-radius: 3px;
  padding: 10px;
  margin-bottom: 10px;
  z-index: 1;
}

.map-overlay-inner fieldset {
  border: none;
  padding: 0;
  margin: 0 0 10px;
  z-index: 1;
}
/* Dark attribution */

.mapboxgl-ctrl.mapboxgl-ctrl-attrib {
  background: rgba(0, 0, 0, .8);
}

.mapboxgl-ctrl.mapboxgl-ctrl-attrib a {
  color: #fff;
}
/* Dark popup */

.mapboxgl-popup-content {
  background-color: #202020;
  color: #fff;
  margin-left: 5px;
  margin-top: 2px;
  margin-bottom: 2px;
  margin-right: 5px;
  z-index: 1000;
}

.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip,
.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip,
.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip {
  border-top-color: #202020;
}

.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip,
.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip,
.mapboxgl-popup-anchor-top .mapboxgl-popup-tip {
  border-bottom-color: #202020;
}

.mapboxgl-popup-anchor-right .mapboxgl-popup-tip {
  border-left-color: #202020;
}

.mapboxgl-popup-anchor-left .mapboxgl-popup-tip {
  border-right-color: #202020;
}

#popup-menu ul,
#menu li {
  margin: 0;
  padding: 0;
  z-index: 100;
}

.mapboxgl-ctrl-group {
  -webkit-filter: invert(100%);
}

.loader {
  margin: -10px 0 0 -250px;
  height: 100px;
  width: 20%;
  position: fixed;
  text-align: center;
  padding: 1em;
  top: 50%;
  left: 50%;
  margin: 0 auto 1em;
  z-index: 9999;
}
/*
Set the color of the icon
*/

svg path,
svg rect {
    fill: #FF6700;
}
<!doctype html lang="de">
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src='https://api.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.css' type='text/css' />
<link href='https://www.mapbox.com/base/latest/base.css' rel='stylesheet' />
</head>
<body>
	<div id="map"></div>
    <div class='map-overlay top'>
        <div class='map-overlay-inner'>
            <fieldset>
                <label><b>Special Map</b></label>
                
            </fieldset>
            <b><a href="x" target="_blank">Some Info</a></b>
        </div>
    </div>
     <div class="loader loader--style1" title="0" id="loader">
        <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="100px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
            <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
    s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
    c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z" />
            <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
    C22.32,8.481,24.301,9.057,26.013,10.047z">
                <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite" />
            </path>
        </svg>
    </div>

所以也许有人可以向我解释实现这一目标的最佳实践。 谢谢

2 个答案:

答案 0 :(得分:0)

您已经添加了源,但是还需要在地图上添加一个图层。您可以使用map.addLayer一步完成这两项操作(请参见Mapbox的example)。

答案 1 :(得分:0)

尝试使用此代码下载geojson并将其显​​示在地图视图上。

guard let url = URL(string: urlString) else { return }
do {
       let data = try Data(contentsOf: url)
       let shape = try MGLShape(data: data, encoding: String.Encoding.utf8.rawValue)
       let shapeClass = shape.classForCoder

       if shapeClass == MGLPointFeature.self {
            if let pointFeature = shape as? MGLPointFeature {
                pointFeature.title = pointFeature.attributes["title"] as? String

                let shapeSource = MGLShapeSource(identifier: "PointShapeSource", shape: pointFeature, options: nil)

                let circleStyleLayer = MGLCircleStyleLayer(identifier: "PointCircleStyleLayer", source: shapeSource)
                circleStyleLayer.circleColor = NSExpression(forConstantValue: UIColor.orange)
                circleStyleLayer.circleStrokeWidth = NSExpression(forConstantValue: 24.0)
                circleStyleLayer.circleStrokeColor = NSExpression(forConstantValue: UIColor(red:1, green:0.76, blue:0.63, alpha:1.0))

                DispatchQueue.main.async(execute: {
                     [unowned self] in
                     self.mapView.setCenter(pointFeature.coordinate, animated: true)
                     self.mapView.style?.addSource(shapeSource)
                     self.mapView.style?.addLayer(circleStyleLayer)
                 })
           }
        }
} catch let error {
}