使用方形而不是点

时间:2014-03-30 10:01:35

标签: javascript leaflet

我使用leafletjs在地图上显示一些点。数据源为geoJSON

与其网站中提供的this简单示例类似。

enter image description here

是否可以使用方形而不是指定样式,或唯一的方法是使用multiPolygon代替multiPoint

1 个答案:

答案 0 :(得分:2)

我希望这会有所帮助:

<强> HTML

<div id="map" style="width: 600px; height: 400px"></div>

<强>的JavaScript

var map = L.map('map').setView([40, -100], 15),
    createSquare = function (latlng, options) {
        var point = map.latLngToContainerPoint(latlng),
            size = options.radius || options.size || 10,
            point1 = L.point(point.x - size, point.y - size),
            point2 = L.point(point.x + size, point.y + size),
            latlng1 = map.containerPointToLatLng(point1),
            latlng2 = map.containerPointToLatLng(point2);
        return new L.rectangle([latlng1, latlng2], options);
    },
    points1 = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [-100, 40]
                }
            },
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [-99.999, 40]
                }
            }
        ]
    },
    points2 = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [-100, 39.999]
                }
            },
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [-99.999, 39.999]
                }
            }
        ]
    },    
    layer1 = L.geoJson(points1, {
        pointToLayer: function (feature, latlng) {
            return new L.CircleMarker(latlng, {
                radius: 10,
                color: "#000",
                weight: 1,
                fillColor: "#F50",
                fillOpacity: 0.75
            });
        }
    }).addTo(map),
    layer2 = L.geoJson(points2, {
        pointToLayer: function (feature, latlng) {
            return createSquare(latlng, {
                radius: 10,
                color: "#000",
                weight: 1,
                fillColor: "#0F5",
                fillOpacity: 0.75
            });
        }
    }).addTo(map);

<强>结果

enter image description here

Here是jsfiddle。