【问题标题】:Get all markers from google map for setting text label从谷歌地图获取所有标记以设置文本标签
【发布时间】:2015-12-04 07:32:25
【问题描述】:

我在使用设置文本标签时遇到问题 https://github.com/googlemaps/js-map-label

使用库设置标签的方法如下:

//var marker = ...
var textLabel = new MapLabel({
    text: 'some text'
    position: position, //google maps LatLng position
    map: map,
    fontSize: 35,
    align: 'right'
});

textLabel.set('position', position);
marker.bindTo('map', textLabel);
marker.bindTo('position', textLabel);

我使用 addGeoJson 方法导入所有数据,但我无权访问标记。有什么办法可以解决这个问题吗?

我需要为显示的每个标记设置一个文本。 这是我当前的实现:

    map.data.addGeoJson(response.data, {idPropertyName: "id"});

    map.data.setStyle(function(feature){
        var color = feature.getProperty('color');
        var zIndex = feature.getProperty('zIndex');

        if(feature.getGeometry().getType().toLowerCase() == "point"){
            return {
                icon: globalOptions.textMarkerPath
            }
        }else{
            return {
                fillColor: 'rgb(' + color + ')',
                strokeColor: 'rgb(' + color + ')',
                fillOpacity: 0.4,
                strokeOpacity: 1,
                strokeWeight: 1,
                zIndex: zIndex
            }
        }

    });

    map.data.forEach(function(feature){
        if(feature.getGeometry().getType().toLowerCase() == "point") {
            var textLabel = new MapLabel({
                text: feature.getProperty("text"),
                position: feature.position,
                map: map,
                fontSize: 35,
                align: 'right'
            });

            textLabel.set('position', feature.position);
            feature.bindTo('map', textLabel);
            feature.bindTo('position', textLabel);
            feature.setProperty('textLabel', textLabel);
        }
    });

再次感谢。

编辑 这是一个 geojson 响应的示例(经过修剪的响应):

{
  "viewable": true,
  "data": {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
          "id": 11766,
          "text": "",
          "layer": "limitaimobil",
          "color": "35,40,50",
          "zIndex": 7,
          "area": 448,
          "is_associated": false
        },
        "geometry": {
          "type": "Polygon",
          "coordinates": [
            [
              [
                26.1373083033642,
                47.7787618059076
              ],
              [
                26.1371254511354,
                47.778684435143
              ],
              [
                26.1370035662918,
                47.7789188945034
              ],
              [
                26.1371962266472,
                47.779000415299
              ],
              [
                26.1373083033642,
                47.7787618059076
              ]
            ]
          ]
        }
      },
      {
        "type": "Feature",
        "properties": {
          "id": 12541,
          "text": "2",
          "layer": "limitaparcela",
          "color": "51,153,255",
          "zIndex": 48,
          "area": 0,
          "is_associated": false
        },
        "geometry": {
          "type": "Point",
          "coordinates": [
            26.1372642328728,
            47.7785316061887
          ]
        }
      }
    ]
  }
}

【问题讨论】:

标签: javascript google-maps google-maps-api-3 google-maps-markers


【解决方案1】:

您可以做的是每次检索标记时将其添加到标记列表中,因此当您需要它们时,您可以使用 id 作为标识符迭代列表并应用文本标签。

编辑:

我是这样做的:

//Used to remember markers
var markerStore = {};

//Time between marker refreshes
var INTERVAL = 250;

function getMarkers() {
    $.ajax({
        type: 'GET',
        url: 'webresources/mobile/retrieve-position',
        contentType: 'application/json',
        dataType: "json", //linea fragril
        beforeSend: function (xhr) {
            // Set the CSRF Token in the header for security
            var token = window.sessionStorage.accessToken;
              if (token) {
                xhr.setRequestHeader('userToken', token);
              }
               else {
                xhr.abort();
            }
        },
        success: function (res, textStatus, jqXHR) {
            if (jqXHR.status !== 204) {
                for (var i = 0; i < res.length; i++) {
                    if (markerStore.hasOwnProperty(res[i].username)) {
                        //Check if marker is still alive
                        if(res[i].alive){

                          Destroy the marker  
                          markerStore[res[i].username].setMap(null);

                        }
                        else{
                            Change markers position reading the new marker information. 
                            markerStore[res[i].username].setPosition(new google.maps.LatLng(res[i].lat, res[i].long));
                        }
                    } 
                    else {
                        //If it doesnt exist, create a new one.
                        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + res[i].color);
                        var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(res[i].lat, res[i].long),
                            title: res[i].username,
                            icon: pinImage,
                            map: map
                        });
                        markerStore[res[i].username] = marker;
                        console.log(marker.getTitle());
                    }
                }
                window.setTimeout(getMarkers, INTERVAL);
            }
        },
        error: function () {

            console.log("Error loading markers.");
        }
    });
}

【讨论】:

  • 我喜欢这样做意味着放弃整个 geojson 的东西并单独解析它,而不是现在它是如何运行的。我仍然会尝试作为最后一个实例
【解决方案2】:

feature 没有position 属性,您需要这样做:

feature.getGeometry().get()

获取与标记关联的google.maps.LatLng

proof of concept fiddle

代码 sn-p:

var map;
var globalOptions = {};

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  map.data.addGeoJson(geoJSON, {
    idPropertyName: "id"
  });

  map.data.setStyle(function(feature) {
    var color = feature.getProperty('color');
    var zIndex = feature.getProperty('zIndex');

    if (feature.getGeometry().getType().toLowerCase() == "point") {
      return {
        icon: globalOptions.textMarkerPath
      }
    } else {
      return {
        fillColor: 'rgb(' + color + ')',
        strokeColor: 'rgb(' + color + ')',
        fillOpacity: 0.4,
        strokeOpacity: 1,
        strokeWeight: 1,
        zIndex: zIndex
      }
    }

  });
  var bounds = new google.maps.LatLngBounds();
  var markerCnt = 0;
  map.data.forEach(function(feature) {
    if (feature.getGeometry().getType().toLowerCase() == "point") {
      bounds.extend(feature.getGeometry().get());
      var textLabel = new MapLabel({
        text: feature.getProperty("text"),
        position: feature.getGeometry().get(),
        map: map,
        fontSize: 35,
        align: 'right'
      });
      markerCnt++;
      if (markerCnt > 1) {
        map.fitBounds(bounds);
      } else {
        map.setCenter(feature.getGeometry().get());
        map.setZoom(6);
      }

      textLabel.set('position', feature.getGeometry().get());
      feature.bindTo('map', textLabel);
      feature.bindTo('position', textLabel);
      feature.setProperty('textLabel', textLabel);
    }
  });


}
google.maps.event.addDomListener(window, "load", initialize);
var geoJSON = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {
      "id": 11766,
      "text": "",
      "layer": "limitaimobil",
      "color": "35,40,50",
      "zIndex": 7,
      "area": 448,
      "is_associated": false
    },
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [
            26.1373083033642,
            47.7787618059076
          ],
          [
            26.1371254511354,
            47.778684435143
          ],
          [
            26.1370035662918,
            47.7789188945034
          ],
          [
            26.1371962266472,
            47.779000415299
          ],
          [
            26.1373083033642,
            47.7787618059076
          ]
        ]
      ]
    }
  }, {
    "type": "Feature",
    "properties": {
      "id": 12541,
      "text": "2",
      "layer": "limitaparcela",
      "color": "51,153,255",
      "zIndex": 48,
      "area": 0,
      "is_associated": false
    },
    "geometry": {
      "type": "Point",
      "coordinates": [
        26.1372642328728,
        47.7785316061887
      ]
    }
  }]
};
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel.js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2019-09-23
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多