在谷歌地图上添加topojson

时间:2017-04-22 15:44:21

标签: json google-maps d3.js google-maps-api-3 topojson

我正在关注这个例子(http://bl.ocks.org/zross/10654766)并试图将加利福尼亚州的数据替换为整个美国的县。我用来替换示例中的数据的是https://d3js.org/us-10m.v1.json。我把它保存为uscounty.json。

我的问题是topojson文件无法与googlemap在正确的位置正确对齐,尽管功能确实显示出来。我想它与投影有关,但我无法弄清楚如何为我想要替换的数据定义正确的投影。

任何意见将不胜感激。

<!DOCTYPE html>
<html>
<head>
  <title>HTML5</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=650, user-scalable=yes">

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
  </script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
  <script src="http://d3js.org/topojson.v1.min.js"></script>

  <style>

    html, body {
      height: 100%;
      margin: 0;
    }

    #mapcanvas{

      height:100%;
    }

  </style>

  <script>


   var geoJsonObject;
   var thejson;

   $(document).ready(function(){



  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(38.284335, -120.833818),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map=new google.maps.Map($('#mapcanvas')[0], mapOptions);

//county.json is a topojson file

  $.getJSON("uscounty.json", function(data){
        geoJsonObject = topojson.feature(data, data.objects.counties)
        map.data.addGeoJson(geoJsonObject); 
      }); 



  });//end document ready


 </script>

</head>
<body>
  <div id="mapcanvas">
  </div>
</body>


</html>

2 个答案:

答案 0 :(得分:0)

你的问题在于你的topojson已被预测。它包含已经用笛卡尔坐标布置的坐标。没有空间参考您的数据,看看Mike Bostock&#39;投射&#39;它在https://github.com/drichardson/examples/blob/master/iconv/utf8-to-utf32.c。他只是通过不为geoPath分配一个空投影来使用空投影:var path = d3.geoPath();。您还可以看到这已经是投影数据,因为坐标值(一旦转换为geojson)不是有效的纬度经度对:[490.18252332008296,270.6981101474867]

空投影获取它所馈送的地理要素中的坐标,并将它们转换为svg坐标,而不进行变换或平移。基本上你只有像素值的topojson。你无法预测它,它已经被预测了。您不了解其投影,因此您无法对其进行投影并重新投影以满足您的需求。你也不知道它使用了什么样的投影,这样你就可以让google地图符合你的topojson。

我建议使用WGS84(lat long pair)找到你感兴趣的区域的geojson,而不是已经投影过的像素坐标。然后你至少可以开始匹配谷歌地图和d3之间的投影。

答案 1 :(得分:0)

我尝试使用topojson而不是geojson,因为县级的geojson使加载过程非常缓慢,但topojson的大小要小得多。

对于遇到同样问题的其他人,我根据人们在线分享的信息和教程找出两种可能的解决方案: 1)我们的topojson文件没有投影(或Albers Projection?):http://bl.ocks.org/mbostock/raw/4090846/us.json(不知道为什么,但它对我在问题中发布的代码很有用) 2)自己从shapefile构建一个topojson:http://blog.mastermaps.com/2013/06/converting-shapefiles-to-topojson.html