简体   繁体   English

如何使用d3.js将纬度和经度转换为(x,y)坐标

[英]How to convert latitude and longitude into (x,y) coordinates using d3.js

I am making my country's map using d3.js. 我正在使用d3.js制作我国家的地图。 I use the google maps url to extract the longitude and latitude values of some points. 我使用谷歌地图网址来提取某些点的经度和纬度值。 In order to show a point using d3, I need to convert it into an (x,y) value in pixels and store it in an array of cities. 为了使用d3显示一个点,我需要将其转换为像素中的(x,y)值并将其存储在城市数组中。 I know this issue is about projection but I couldn't manage to solve it. 我知道这个问题是关于投影但我无法解决它。

This is part of my code. 这是我的代码的一部分。

var projection = d3.geoMercator().fitSize([width, height], json);
var path = d3.geoPath().projection(projection); 


var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

console.log(coords[0]); 
console.log(coords[1]); 

cities.push([coords[0], coords[1]]);

You don't need to convert your data to (x,y) pairs in pixels. 您无需将数据转换为(x,y)对(以像素为单位)。 When you use d3.geoPath.projection(projection) you've set your d3.geoPath() path generator to use the specified projection to automatically convert (latitude, longitude) pairs to (x,y) pairs. 当您使用d3.geoPath.projection(projection)您已设置d3.geoPath()路径生成器以使用指定的投影自动将(纬度,经度)对转换为(x,y)对。

What you need to do is take your (lat, long) pairs and use them to generate a GeoJSON object, which you can then feed to your d3.geoPath generator. 您需要做的是获取(lat,long)对并使用它们生成GeoJSON对象,然后可以将其提供给d3.geoPath生成器。 You'll probably want a GeoJSON point . 你可能想要一个GeoJSON点

So your code should probably look like: 所以你的代码可能应该是这样的:

var projection = d3.geoMercator().fitSize([width, height], json);
var pathGenerator = d3.geoPath(projection);

var URL =  "https://www.google.com.tr/maps/place/Ankara/@39.9035553,32.6223376,11z/data=!3m1!4b1!4m5!3m4!1s0x14d347d520732db1:0xbdc57b0c0842b8d!8m2!3d39.9333635!4d32.8597419?hl=tr";

var splitUrl = URL.split('@');
var coords = splitUrl[1].split(',');

var geoJsonPoint = {
    type: "Point",
    coordinates: coords,
} 

pathGenerator.path(geoJsonPoint);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM