Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

html - On a Google maps overlay, how do I create lines between svg elements in D3

I'm new to D3 and I want to call my function drawlink to draw lines between some of my elements. I tried adding an each call to my link variable to call it, i.e.:

  var link = layer.selectAll(".link")
      .data(data.links)
    .enter().append("line")
      .attr("class", "link")
      .each(drawlink);

but that did not work. Before I add that line I have got the stage where the Google Map has drawn and my 4 svg elements have been drawn.

How should I be doing this ? Other code improvement comments very welcome too.

stations.json

{
  "nodes":[
    {"name":"A","long":0.0000,"lat":51.4800},
    {"name":"B","long":-0.1684,"lat":51.4875},
    {"name":"C","long":-0.2043,"lat":51.5096},
    {"name":"D","long":-0.1269,"lat":51.5295}
  ],
  "links":[
    {"source":0,"target":1},
    {"source":0,"target":2},
    {"source":0,"target":3},
    {"source":2,"target":3} 
  ]
}

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>

<style>
html, body, #map {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.link {
  stroke: #ccc;
  stroke-width: 1.5px;
}

.stations, .stations svg {
  position: absolute;
}

.stations svg {
  width: 60px;
  height: 20px;
  padding-right: 100px;
  font: 12px sans-serif;
}

.stations circle {
  fill: brown;
  stroke: black;
  stroke-width: 1.5px;
}

</style>

</head>
<body>
<div id="map" style="width: 1200px; height: 600px;"></div>
<script type="text/javascript">

// Create the Google Map…
var map = new google.maps.Map(d3.select("#map").node(), {
  zoom: 12,
  center: new google.maps.LatLng(51.5195, -0.1269),
  mapTypeId: google.maps.MapTypeId.TERRAIN
});

d3.json("stations.json", function(error, data) {
  if (error) throw error;

  var overlay = new google.maps.OverlayView();

  overlay.onAdd = function() {
    var layer = d3.select(this.getPanes().overlayLayer).append("div")
        .attr("class", "stations");

    overlay.draw = function() {
      var projection = this.getProjection(),
          padding = 10;

      var node = layer.selectAll(".stations")
          .data(data.nodes)
          .each(transform)
        .enter().append("svg")
          .each(transform)
          .attr("class", "node");

      var link = layer.selectAll(".link")
          .data(data.links)
        .enter().append("line")
          .attr("class", "link");

      node.append("circle")
          .attr("r", 4.5)
          .attr("cx", padding)
          .attr("cy", padding);

      node.append("text")
          .attr("x", padding + 7)
          .attr("y", padding)
          .attr("dy", ".31em")
          .text(function(d) { return d.name; });

      function transform(d) {
        d = new google.maps.LatLng(d.lat, d.long);
        d = projection.fromLatLngToDivPixel(d);
        return d3.select(this)
            .style("left", (d.x - padding) + "px")
            .style("top", (d.y - padding) + "px");
      }

      function drawlink(d) {
        link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });
        }     
    };
  };

  overlay.setMap(map);
});

</script>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd make a slight deviation in your approach. Instead of appending an svg per station, I'd append a single svg (if you need to draw lines from station to station you'll have to do this) and then append a g per station. The lines then are an easy loop over your links, calculate position and add the lines:

Here's the 3 main positioning functions then:

  function latLongToPos(d){
    var p = new google.maps.LatLng(d.lat, d.long);
    p = projection.fromLatLngToDivPixel(p);
    p.x = p.x - padding;
    p.y = p.y - padding;
    return p;
  }

  function transform(d) {
    var p = latLongToPos(d);
    return d3.select(this)
      .attr("transform","translate(" + p.x + "," + p.y + ")");
  }

  function drawlink(d) {
    var p1 = latLongToPos(data.nodes[d.source]),
        p2 = latLongToPos(data.nodes[d.target]);
    d3.select(this)
      .attr('x1', p1.x)
      .attr('y1', p1.y)
      .attr('x2', p2.x)
      .attr('y2', p2.y)
      .style('fill', 'none')
      .style('stroke', 'steelblue');

Full code:

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<html>

<head>
  <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script src="http://d3js.org/d3.v3.min.js"></script>

  <style>
    html,
    body,
    #map {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    .link {
      stroke: #ccc;
      stroke-width: 1.5px;
    }
    
    .stations,
    .stations svg {
      position: absolute;
    }
    
    .stations svg {
      width: 1200px;
      height: 600px;
      padding-right: 100px;
      font: 12px sans-serif;
    }
    
    .stations circle {
      fill: brown;
      stroke: black;
      stroke-width: 1.5px;
    }
  </style>

</head>

<body>
  <div id="map" style="width: 1200px; height: 600px;"></div>
  <script type="text/javascript">
    // Create the Google Map…
    var map = new google.maps.Map(d3.select("#map").node(), {
      zoom: 12,
      center: new google.maps.LatLng(51.5195, -0.1269),
      mapTypeId: google.maps.MapTypeId.TERRAIN
    });

    //d3.json("stations.json", function(error, data) {

    var data = {
      "nodes": [{
        "name": "A",
        "long": 0.0000,
        "lat": 51.4800
      }, {
        "name": "B",
        "long": -0.1684,
        "lat": 51.4875
      }, {
        "name": "C",
        "long": -0.2043,
        "lat": 51.5096
      }, {
        "name": "D",
        "long": -0.1269,
        "lat": 51.5295
      }],
      "links": [{
        "source": 0,
        "target": 1
      }, {
        "source": 0,
        "target": 2
      }, {
        "source": 0,
        "target": 3
      }, {
        "source": 2,
        "target": 3
      }]
    }

    var overlay = new google.maps.OverlayView();

    overlay.onAdd = function() {
      var layer = d3.select(this.getPanes().overlayLayer).append("div")
        .attr("class", "stations");

      overlay.draw = function() {
        
        layer.select('svg').remove();
        
        var projection = this.getProjection(),
          padding = 10;

        var svg = layer.append("svg")
          .attr('width', 1200)
          .attr('height', 600)

        var node = svg.selectAll(".stations")
          .data(data.nodes)
          .enter().append("g")
          .each(transform)
          .attr("class", "node");

        var link = svg.selectAll(".link")
          .data(data.links)
          .enter().append("line")
          .attr("class", "link")
          .each(drawlink);

        node.append("circle")
          .attr("r", 4.5);

        node.append("text")
          .attr("x", 7)
          .attr("y", 0)
          .attr("dy", ".31em")
          .text(function(d) {
            return d.name;
          });

        function latLongToPos(d) {
          var p = new google.maps.LatLng(d.lat, d.long);
          p = projection.fromLatLngToDivPixel(p);
          p.x = p.x - padding;
          p.y = p.y - padding;
          return p;
        }

        function transform(d) {
          var p = latLongToPos(d);
          return d3.select(this)
            .attr("transform", "translate(" + p.x + "," + p.y + ")");
        }

        function drawlink(d) {
          var p1 = latLongToPos(data.nodes[d.source]),
            p2 = latLongToPos(data.nodes[d.target]);
          d3.select(this)
            .attr('x1', p1.x)
            .attr('y1', p1.y)
            .attr('x2', p2.x)
            .attr('y2', p2.y)
            .style('fill', 'none')
            .style('stroke', 'steelblue');
        }
      };
    };

    overlay.setMap(map);
    //});
  </script>
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...