Scale a circle's radius (given in meters) to D

2019-05-22 18:32发布

问题:

I am using D3.js and TopoJSON libraries to render a flat SVG map of the world in a small div on a web page. I'm also taking some geographic objects (polygons and circles), and plotting them on this map via lat/long coordinates. This all seems to be working pretty well, however, the circle objects that I am plotting on the map contain a radius element which is given in meters. I cannot find or figure out how to convert/scale this measurement appropriately onto the SVG map. Any help would be greatly appreciated.

The snippet of code that is drawing the circle and setting is:

if (formattedGeoObjects[a].shape.indexOf('circle') >= 0) {
  //plot point for circle
  svg.selectAll('.pin')
    .data(formattedGeoObjects).enter().append('circle', '.pin')
    .attr({fill: formattedGeoObjects[a].color.toString()})
    .attr('r', 5) //formattedGeoObjects[a].radius is in meters
    .attr('transform', 'translate(' +
      projection([
        formattedGeoObjects[a].location[0],
        formattedGeoObjects[a].location[1]
      ]) + ')'
    );
}

JSFiddle link for condensed version of the code: https://jsfiddle.net/vnrL0fdc/7/

Here's the full code for reference...

Function that does the bulk of the work:

setupMap: function(mapJson, theElement, geoObject, colorCb, normalizeCb) {
    var width = 200;
    var height = 120;

    //define projection of spherical coordinates to Cartesian plane
    var projection = d3.geo.mercator().scale((width + 1) / 2 / Math.PI).translate([width / 2, height / 2]);

    //define path that takes projected geometry from above and formats it appropriately
    var path = d3.geo.path().projection(projection);

    //select the canvas-svg div and apply styling attributes
    var svg =
      d3.select('#' + theElement + ' .canvas-svg').append('svg')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'ocean');

    //convert the topoJSON back to GeoJSON
    var countries = topojson.feature(mapJson, mapJson.objects.countries).features;

    //give each country its own path element and add styling
    svg.selectAll('.countries')
      .data(countries).enter().append('path')
      .attr('class', 'country')
      .attr('d', path);

    //add borders around all countries with mesh
    svg.append('path')
      .datum(topojson.mesh(mapJson, mapJson.objects.countries, function() {
        return true;
      }))
      .attr('d', path)
      .attr('class', 'border');

    //if shape data exists, draw it on the map
    if (geoObject !== null && geoObject.length !== 0) {
      //normalize geoObject into format needed for d3 arc functionality and store each shapes color
      var formattedGeoObjects = normalizeCb(geoObject, colorCb);

      for (a = 0; a < formattedGeoObjects.length; a++) {
        if (formattedGeoObjects[a].shape.indexOf('polygon') >= 0) {
          for (b = 0; b < formattedGeoObjects[a].lines.length; b++) {
            //plot point for polygon
            svg.selectAll('.pin')
              .data(formattedGeoObjects).enter().append('circle', '.pin')
              .style({fill: formattedGeoObjects[a].color.toString()}).attr('r', 2)
              .attr('transform', 'translate(' +
                projection([
                  formattedGeoObjects[a].lines[b].coordinates[0][0],
                  formattedGeoObjects[a].lines[b].coordinates[0][1]
                ]) + ')'
              );
          }
          //draw lines for polygon
          svg.append('g').selectAll('.arc')
            .data(formattedGeoObjects[a].lines).enter().append('path')
            .attr({d: path})
            .style({
              stroke: formattedGeoObjects[a].color.toString(),
              'stroke-width': '1px'
            });
        }
        if (formattedGeoObjects[a].shape.indexOf('circle') >= 0) {
          //plot point for circle
          svg.selectAll('.pin')
            .data(formattedGeoObjects).enter().append('circle', '.pin')
            .attr({fill: formattedGeoObjects[a].color.toString()})
            .attr('r', 5)
            .attr('transform', 'translate(' +
              projection([
                formattedGeoObjects[a].location[0],
                formattedGeoObjects[a].location[1]
              ]) + ')'
            );
        }
      }
    }
  }

Here is a condensed version of what the formattedGeoObjects looks like:

[
  {
    "shape": "polygon0",
    "color": "#000000",
    "lines": [
      {
        "type": "LineString",
        "coordinates": [
          [
            -24.9609375,
            36.5625
          ],
          [
            -24.9609375,
            55.1953125
          ]
        ]
      }
      ..... more coords
    ]
  },
  {
    "shape": "polygon1",
    "color": "#006600",
    "lines": [
      {
        "type": "LineString",
        "coordinates": [
          [
            -42.1875,
            26.3671875
          ],
          [
            -71.71875,
            7.734375
          ]
        ]
      }
      ..... more coordindates
    ]
  },
  {
    "shape": "circle2",
    "color": "#FF0000",
    "location": [
      13.359375,
      31.640625
    ],
    "radius": 1881365.33
  }
]

And lastly, the CSS/HTML:

.canvas-svg {
  .ocean {
    background: #85E0FF;
  }
  .country {
    fill: #FFFFFF;
  }
  .border {
    fill: none;
    stroke: #777;
    stroke-width: .5;
  }
}

<div class="canvas-svg"></div>

回答1:

A colleague of mine helped me out by showing me a much simpler way to do this (FYI - there has been an update to the lat/lon for the center of the circle). Plotting two points on the canvas and computing the distance to find the scale works and is accurate - but there is a much more simple way of doing it using the total pixels in the image and the total area of the world, code snippets and JSFiddle below:

var width = 200;
var height = 120;

//variables for scaling circle radius
var totPixels = (width * height);
var totWorldMeters = 510000000000;
var metersPerPixel = (totWorldMeters / totPixels);
var scaledRadius;

//scale the radius given in meters to pixels on the map
scaledRadius = (100 * (formattedGeoObjects[a].radius / metersPerPixel));
if(scaledRadius < 2) {
    scaledRadius = 2;
}

Working JSFiddle: https://jsfiddle.net/vnrL0fdc/15/



回答2:

So, I "think" I've found a way to scale the radius (given in meters) to the pixels on the Cartesian plane d3 geo map. I'm probably making this way more complicated than it needs to be - but I'm not sure how else to do it.

The map's height, width, and projection is defined as:

var width = 200;
var height = 120;
var projection = 
    d3.geo.mercator()
    .scale((width + 1) / 2 / Math.PI)
    .translate([width / 2, height / 2]);

The geo objects that I'm plotting on the map contain lat/long coordinates for multiple points. By searching on stackoverflow, I found a distance formula:

d = sqrt((x2 - x1)^2 + (y2 - y1)^2)

The formula requires two points from the cartesian plane (x1,y1) and (x2,y2). I picked the circle's point and one of the polygon points, the lat/long coordinates are as follows:

Lat/Long for polygon1, point1: 36.5625, -24.9609375
Lat/Long for circle: 31.640625, 13.359375

I used the following web site to find out how many miles it is between the two coordinates above - http://www.freemaptools.com/how-far-is-it-between.htm

Miles between the two coordinates on the map are: 3020.207

Then I found the projected coordinates (x,y) on the Cartesian plane for the two lat/long coordinates via:

projection([long,lat])
X/Y for polygon1, point1: 86.0634765625, 38.040230671805666
X/Y for circle: 107.458984375, 41.36090550209383

So, I then plugged these values into the formula to calculate the pixel distance between the two points:

d = sqrt ( (107.458984375 - 86.0634765625)^2 + (41.36090550209383 - 38.040230671805666)^2  )
result = 21.651665891641176 pixels
miles per pixel = 139.49074473599643 (calculated by: 3020.207/21.651665891641176)
meters per pixel = 224488.5930964074505 (calculated by 139.49074473599643 * 1609.34)

Working JSFiddle: https://jsfiddle.net/vnrL0fdc/8/

This seems like an awfully roundabout way to scale meters to a mercator map projection. If anyone has a much simpler solution - please share!