mapbox初步使用

mapbox初步使用

DOCTYPE html>
<html>

<head>
  <meta charset='utf-8' />
  <title>改变一个地图的样式title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.5.0/mapbox-gl.css" rel="stylesheet">
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.5.0/mapbox-gl.js">script>
  <script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.3.0/mapbox-gl-draw.js'>script>
  <link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.3.0/mapbox-gl-draw.css'
    type='text/css' />
  <script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.min.js'>
  script>
  <link rel='stylesheet'
    href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.css'
    type='text/css' />
  <script src="js/jquery-1.11.1.min.js">script>
  <script src="js/turf.min.js">script>

  <style>
    body {
      margin: 0;
      padding: 0;
    }

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

    .geocoder {
      position: absolute;
      z-index: 1;
      width: 50%;
      left: 50%;
      margin-left: -25%;
      top: 20px;
    }

    .mapboxgl-ctrl-geocoder {
      min-width: 100%;
    }

    .marker {
      background-image: url('./img/water.png');
      background-size: cover;
      width: 30px;
      height: 36px;
      cursor: pointer;
    }
  style>
head>

<body>

  <style>
    #menu {
      position: absolute;
      background: #fff;
      padding: 10px;
      font-family: 'Open Sans', sans-serif;
    }

    #sourse {
      position: absolute;
      bottom: 200px;
      background: #fff;
      padding: 10px;
      font-family: 'Open Sans', sans-serif;
    }
  style>

  <style>
    .measure-result {
      background-color: white;
      border-radius: 3px;
      height: 16px;
      line-height: 16px;
      padding: 0 3px;
      font-size: 12px;
      box-shadow: 0 0 0 1px #ccc;
    }

    .close {
      cursor: pointer;
      width: 14px;
      height: 14px;
      line-height: 16px;
      text-align: center;
      padding: 0;
    }
  style>

  <div id='map'>div>
  <div id="geocoder" class="geocoder">div>
  <div id='menu'>
    <input id='streets-v11' type='radio' name='rtoggle' value='streets'>
    <label for='streets'>街道label>
    <input id='satellite-v9' type='radio' name='rtoggle' value='satellite'>
    <label for='satellite'>卫星label>
    <input id='3d' type='radio' name='rtoggle' value='3d' checked='checked'>
    <label for='3d'>3Dlabel>
  div>

  <div id="sourse">
    <input type="checkbox" name="" id="Water"> 水源
    <input type="checkbox" name="" id="Area"> 区域
    <input type="checkbox" name="" id="Section"> 切片
    <input type="button" name="" value="测距" onclick="measureLength()">
    <input type="button" name="" value="测面" onclick="measureArea()">
  div>
  <script>
    mapboxgl.accessToken =
      'pk.eyJ1IjoibGl1d2FubGkiLCJhIjoiY2tzczloYXhqMHVtZTJucHVndGo1cHA2bSJ9.77f8qFnHHiNSUTaLCKFZGg';
    // 创建地图
    var map = new mapboxgl.Map({
      container: 'map',
      // style: 'mapbox://styles/mapbox/satellite-v9',
      zoom: 13,
      center: [122.027913, 37.428458],
      pitch: 85, // pitch in degrees
      bearing: 25, // bearing in degrees
      style: 'mapbox://styles/mapbox-map-design/ckhqrf2tz0dt119ny6azh975y',

    });

    // 添加选择地图控件
    var layerList = document.getElementById('menu');
    var inputs = layerList.getElementsByTagName('input');

    function switchLayer(layer) {
      var layerId = layer.target.id;
      // console.log(layerId)
      if (layerId == '3d') {
        map.setStyle('mapbox://styles/mapbox-map-design/ckhqrf2tz0dt119ny6azh975y');
        add3DSource();
      } else {
        map.setStyle('mapbox://styles/mapbox/' + layerId);
      }
    }

    for (var i = 0; i < inputs.length; i++) {
      inputs[i].onclick = switchLayer;
    }

    // 添加导航与全屏按钮
    var nav = new mapboxgl.NavigationControl();
    map.addControl(nav, 'bottom-right');
    map.addControl(new mapboxgl.FullscreenControl(), 'bottom-right');

    // 添加定位工具
    map.addControl(new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true
      },
      trackUserLocation: true,
      showUserHeading: true
    }));

    // 添加搜索框
    var geocoder = new MapboxGeocoder({
      accessToken: mapboxgl.accessToken,
      mapboxgl: mapboxgl
    });

    document.getElementById('geocoder').appendChild(geocoder.onAdd(map));

    // 添加绘图工具
    var draw = new MapboxDraw({
      displayControlsDefault: false,
      controls: {
        polygon: true,
        line_string: true,
        point: true,
        trash: true
      }
    });

    map.addControl(draw);
    map.on('draw.create', updateArea);
    map.on('draw.delete', updateArea);
    map.on('draw.update', updateArea);

    function updateArea(e) {
      var data = draw.getAll();
      var answer = document.getElementById('calculated-area');
      if (data.features.length > 0) {
        var area = turf.area(data);
        // restrict to area to 2 decimal points
        var rounded_area = Math.round(area * 100) / 100;
        answer.innerHTML = '

' + rounded_area + '

square meters

'
; } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert('Use the draw tools to draw a polygon!'); } } var geojson = { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "message": "Foo", "iconSize": [60, 60] }, "geometry": { "type": "Point", "coordinates": [ 122.114322, 37.518263 ] } }, { "type": "Feature", "properties": { "message": "Bar", "iconSize": [50, 50] }, "geometry": { "type": "Point", "coordinates": [ -61.2158203125, -15.97189158092897 ] } }, { "type": "Feature", "properties": { "message": "Baz", "iconSize": [40, 40] }, "geometry": { "type": "Point", "coordinates": [ -63.29223632812499, -18.28151823530889 ] } } ] }; let mapMarkers = [] let MapOption = [] let MapSection = [] let water; map.on('load', function () { // addSourceWater(); // addSourcePloygon(); add3DSource(); addSection(); }); function addSection() { map.addLayer({ "id": "chicago", "source": { "type": "raster", "url": 'mapbox://liuwanli.aqea10ww' }, "type": "raster" }); MapSection.push("chicago") } $("#Section").on('click', function () { console.log(MapSection) if ($(this).is(":checked")) { addSection(); } else { ClearSection(); } }) $("#Water").on('click', function () { if ($(this).is(":checked")) { addSourceWater(); } else { MapClear('szmarker') } }) $("#Area").on('click', function () { if ($(this).is(":checked")) { addSourcePloygon(); } else { ClearPloygon(); } }) // 标记点清空方法 function MapClear(option) { if (option == "szmarker") { mapMarkers.forEach((option) => option.remove()) mapMarkers = [] } } // 区域或线清空方法 function ClearPloygon() { MapOption.forEach(function (item) { map.removeLayer(item); map.removeSource(item); }) MapOption = [] } function ClearSection() { MapSection.forEach(function (item) { map.removeLayer(item); map.removeSource(item); }) MapSection = [] } // 添加水源点 function addSourceWater() { for (const { geometry, properties } of geojson.features) { const el = document.createElement('div'); el.className = 'marker'; el.addEventListener('click', function () { window.alert(properties.message); }); szmarker = new mapboxgl.Marker(el) .setLngLat(geometry.coordinates) .addTo(map); mapMarkers.push(szmarker) } } // 添加3d图层 function add3DSource() { map.addSource('mapbox-dem', { 'type': 'raster-dem', 'url': 'mapbox://mapbox.mapbox-terrain-dem-v1', 'tileSize': 512, 'maxzoom': 14 }); // add the DEM source as a terrain layer with exaggerated height map.setTerrain({ 'source': 'mapbox-dem', 'exaggeration': 1.5 }); // add a sky layer that will show when the map is highly pitched map.addLayer({ 'id': 'sky', 'type': 'sky', 'paint': { 'sky-type': 'atmosphere', 'sky-atmosphere-sun': [0.0, 0.0], 'sky-atmosphere-sun-intensity': 15 } }); } // 添加线 function addSourcePloygon() { console.log(1) let id = "jkfafhas"; ploygon = map.addLayer({ 'id': id, 'type': 'line', 'source': { 'type': 'geojson', 'data': { 'type': 'Feature', 'geometry': { 'type': 'LineString', 'coordinates': [ [121.93383111849488, 37.45828387182776], [121.9242300852128, 37.368160147509585], [122.1354528174246, 37.33485629166387], [122.14418102949998, 37.46798303489592], [121.93383111849488, 37.45828387182776] ] } } }, "layout": { "line-join": "round", "line-cap": "round" }, "paint": { "line-color": "red", "line-width": 3 } }); MapOption.push(id) } // 测量距离 function measureLength() { var isMeasure = true; // 禁止双击缩放 map.doubleClickZoom.disable(); map.getCanvas().style.cursor = 'default'; function clearMeasure() { $(".measure-result").remove(); var source = map.getSource('points'); var json = { 'type': 'FeatureCollection', 'features': [] }; if (source) { map.getSource('points').setData(json); map.getSource('line-move').setData(json); map.getSource('line').setData(json); } var sourceArea = map.getSource('points-area'); if (sourceArea) { map.getSource('points-area').setData(json); map.getSource('line-area').setData(json); } } clearMeasure(); var jsonPoint = { 'type': 'FeatureCollection', 'features': [] }; var jsonLine = { 'type': 'FeatureCollection', 'features': [] }; var points = []; const ele = document.createElement('div'); ele.setAttribute('class', 'measure-result'); const option = { element: ele, anchor: 'left', offset: [8, 0] }; var tooltip = new mapboxgl.Marker(option) .setLngLat([0, 0]) .addTo(map); var markers = []; var source = map.getSource('points'); if (source) { map.getSource('points').setData(jsonPoint); map.getSource('line-move').setData(jsonLine); map.getSource('line').setData(jsonLine); } else { map.addSource('points', { type: 'geojson', data: jsonPoint }); map.addSource('line', { type: 'geojson', data: jsonLine }); map.addSource('line-move', { type: 'geojson', data: jsonLine }); map.addLayer({ id: 'line-move', type: 'line', source: 'line-move', paint: { 'line-color': '#ff0000', 'line-width': 2, 'line-opacity': 0.65 } }); map.addLayer({ id: 'line', type: 'line', source: 'line', paint: { 'line-color': '#ff0000', 'line-width': 2, 'line-opacity': 0.65 } }); map.addLayer({ id: 'points', type: 'circle', source: 'points', paint: { 'circle-color': '#ffffff', 'circle-radius': 3, 'circle-stroke-width': 2, 'circle-stroke-color': '#ff0000' } }); } function addPoint(coords) { if (jsonPoint.features.length > 0) { var prev = jsonPoint.features[jsonPoint.features.length - 1]; jsonLine.features.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: [prev.geometry.coordinates, coords] } }); map.getSource('line').setData(jsonLine); } jsonPoint.features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: coords } }); map.getSource('points').setData(jsonPoint); } function getLength(coords) { var _points = points.concat([coords]); console.log("points" + points); console.log("coords" + coords); console.log("_points" + _points); var line = turf.lineString(_points); var len = turf.length(line); if (len < 1) { len = Math.round(len * 1000) + 'm'; } else { len = len.toFixed(2) + 'km'; } return len; } function addMeasureRes(coords) { const ele = document.createElement('div'); ele.setAttribute('class', 'measure-result'); const option = { element: ele, anchor: 'left', offset: [8, 0] }; ele.innerHTML = points.length === 0 ? '起点' : getLength(coords); var marker = new mapboxgl.Marker(option) .setLngLat(coords) .addTo(map); markers.push(marker); } map.on('click', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; addMeasureRes(coords); addPoint(coords); points.push(coords); } }); map.on('mousemove', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; if (jsonPoint.features.length > 0) { var prev = jsonPoint.features[jsonPoint.features.length - 1]; var json = { type: 'Feature', geometry: { type: 'LineString', coordinates: [prev.geometry.coordinates, coords] } }; map.getSource('line-move').setData(json); ele.innerHTML = getLength(coords); } else { ele.innerHTML = '点击地图开始测量'; } tooltip.setLngLat(coords); } }); map.on('dblclick', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; addPoint(coords); isMeasure = false; map.getCanvas().style.cursor = ''; jsonPoint.features = []; jsonLine.features = []; tooltip.remove(); // 添加关闭按钮 const ele = document.createElement('div'); ele.setAttribute('class', 'measure-result close'); const option = { element: ele, anchor: 'bottom-left', offset: [-5, -10] }; ele.innerHTML = '×'; new mapboxgl.Marker(option) .setLngLat(coords) .addTo(map); ele.onclick = function (__e) { __e.stopPropagation(); map.doubleClickZoom.enable(); clearMeasure(); } } }); } // 测量距离 function measureArea() { var isMeasure = true; // 禁止双击缩放 map.doubleClickZoom.disable(); map.getCanvas().style.cursor = 'default'; function clearMeasure() { $(".measure-result").remove(); var source = map.getSource('points'); var json = { 'type': 'FeatureCollection', 'features': [] }; if (source) { map.getSource('points').setData(json); map.getSource('line-move').setData(json); map.getSource('line').setData(json); } var sourceArea = map.getSource('points-area'); if (sourceArea) { map.getSource('points-area').setData(json); map.getSource('line-area').setData(json); } } clearMeasure(); var jsonPoint = { 'type': 'FeatureCollection', 'features': [] }; var jsonLine = { 'type': 'FeatureCollection', 'features': [] }; var points = []; var ele = document.createElement('div'); ele.setAttribute('class', 'measure-result'); const option = { element: ele, anchor: 'left', offset: [8, 0] }; var tooltip = new mapboxgl.Marker(option) .setLngLat([0, 0]) .addTo(map); var source = map.getSource('points-area'); if (source) { map.getSource('points-area').setData(jsonPoint); map.getSource('line-area').setData(jsonLine); } else { map.addSource('points-area', { type: 'geojson', data: jsonPoint }); map.addSource('line-area', { type: 'geojson', data: jsonLine }); map.addLayer({ id: 'line-area', type: 'fill', source: 'line-area', paint: { 'fill-color': '#ff0000', 'fill-opacity': 0.1 } }); map.addLayer({ id: 'line-area-stroke', type: 'line', source: 'line-area', paint: { 'line-color': '#ff0000', 'line-width': 2, 'line-opacity': 0.65 } }); map.addLayer({ id: 'points-area', type: 'circle', source: 'points-area', paint: { 'circle-color': '#ffffff', 'circle-radius': 3, 'circle-stroke-width': 2, 'circle-stroke-color': '#ff0000' } }); } function getArea(coords) { var pts = points.concat([coords]); pts = pts.concat([points[0]]); var polygon = turf.polygon([pts]); var area = turf.area(polygon); if (area < 1000) { area = Math.round(area) + 'm²'; } else { area = (area / 1000000).toFixed(2) + 'km²'; } return area; } function addPoint(coords) { jsonPoint.features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: coords } }); map.getSource('points-area').setData(jsonPoint); } map.on('click', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; points.push(coords); addPoint(coords); } }); map.on('dblclick', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; points.push(coords); isMeasure = false; ele.innerHTML = getArea(coords); tooltip.setLngLat(coords); // 添加关闭按钮 var _ele = document.createElement('div'); _ele.setAttribute('class', 'measure-result close'); var option = { element: _ele, anchor: 'bottom-left', offset: [-5, -10] }; _ele.innerHTML = '×'; new mapboxgl.Marker(option) .setLngLat(coords) .addTo(map); _ele.onclick = function (__e) { __e.stopPropagation(); map.doubleClickZoom.enable(); clearMeasure(); } } }); map.on('mousemove', function (_e) { if (isMeasure) { var coords = [_e.lngLat.lng, _e.lngLat.lat]; var len = jsonPoint.features.length; if (len === 0) { ele.innerHTML = '点击地图开始测量'; } else if (len === 1) { ele.innerHTML = '点击地图继续绘制'; } else { var pts = points.concat([coords]); pts = pts.concat([points[0]]); var json = { type: 'Feature', geometry: { type: 'Polygon', coordinates: [pts] } }; map.getSource('line-area').setData(json); ele.innerHTML = getArea(coords); } tooltip.setLngLat(coords); } }); }
script> body> html>

你可能感兴趣的:(笔记,html,css,html5)