带有 D3js 的引脚标记

Pin Markers with D3js

本文关键字:引脚 D3js 带有      更新时间:2023-09-26

我正在实现一张地图,该地图将按纬度和经度进行标记。我正在使用 D3Js 从 topojson 文件创建 svg。

这是实现:

var places = [
        {
            name: "Longo, England",
            location: {
                latitude: 51.5,
                longitude: -0.116667
            }
        },
        {
            name: "Dublin, Irland",
            location: {
                latitude: 53.428590,
                longitude: -6.188024
            }
        }
    ]
    var margin = {top: 10, left: 10, bottom: 10, right: 10};
    var width = parseInt(d3.select('#map').style('width'));
    width = width - margin.left - margin.right;
    var mapRatio = 1;
    var height = width * mapRatio;
    var svg = d3.select("#map").append("svg")
        .attr("width", width)
        .attr("height", height);
    d3.json("data/uk.json", function(error, uk) {
        if (error) return console.error(error);
        var subunits = topojson.feature(uk, uk.objects.subunits);
        var projection = d3.geo.mercator()
            .center([0, 55.4])
            .rotate([4.4, 0])
            .scale(500)
            .translate([width / 2, height / 2]);
        var path = d3.geo.path()
            .projection(projection);
        svg.append("path")
            .datum(subunits)
            .attr("d", path)
            .attr("class", "subunit-boundary IRL");
        svg.selectAll(".subunit")
            .data(topojson.feature(uk, uk.objects.subunits).features)
            .enter().append("path")
            .attr("class", function(d) { return "subunit " + d.id; })
            .attr("d", path);
        svg.selectAll(".pin")
            .data(places)
            .enter()
            .append('image')
            .attr('class', 'datamaps-pin')
            .attr('xlink:href', 'http://a.tiles.mapbox.com/v3/marker/pin-m+7e7e7e@2x.png')
            .attr('height', 40)
            .attr('width', 40)
            .attr("transform", function(d) {
                return "translate(" + projection([
                        d.location.longitude,
                        d.location.latitude
                    ]) + ")"
            });

但是,引脚已错位。

当我更改简单点的标记时,它应该在正确的位置

svg.selectAll(".pin")
            .data(places)
            .enter().append("circle", ".pin")
            .attr("r", 5)
            .attr("transform", function(d) {
                return "translate(" + projection([
                        d.location.longitude,
                        d.location.latitude
                    ]) + ")"
            });

如果未指定任何 x 或 y,则以原点 (x,y = 0) 为中心绘制一个圆。但是,如果未指定 x 或 y,则会在原点绘制图像的左上角。

要获得与圆圈相同的效果,请添加

.attr("x", -20)
.attr("y", -20)

到图钉的图像版本。