Sau*_*kar 8 javascript gis tooltip d3.js
我使用D3和国家geojson创建了一个基本地图.这是演示.
现在,当用户点击地图上的任何坐标时,我会在工具提示中显示天气信息,并以天气图标作为标记.
countries = countriesGroup
.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.attr("id", function(d, i) {
return "country" + d.properties.iso_a3;
})
.attr("class", "country")
// add a mouseover action to show name label for feature/country
.on("mouseover", function(d, i) {
d3.select("#countryLabel" + d.properties.iso_a3).style("display", "block");
})
.on("mouseout", function(d, i) {
d3.select("#countryLabel" + d.properties.iso_a3).style("display", "none");
})
// add an onclick action to zoom into clicked country
.on("click", function(d, i) {
var eventLocation = d3.mouse(this);
var coordinates = projection.invert(eventLocation);
var proxy = "https://cors-anywhere.herokuapp.com/";
var wetherInfoUrl =
"https://api.darksky.net/forecast/c68e9aaf0d467528b9363e383bde6254/" + coordinates[1] + "," + coordinates[0] + "?exclude=minutely,hourly,daily";
$.ajax({
url: proxy + wetherInfoUrl,
success: function(response) {
tooltipDiv
.transition()
.duration(200)
.style("opacity", 0.9);
tooltipDiv
.html('<h3>Dynamic Weather info: '+ response.currently.humidity +'</h3><br/><img src="https://darksky.net/images/weather-icons/' + response.currently.icon + '.png" alt="clear-night Icon" width="50" height="50">')
.style("left", (eventLocation[0] - 250) + "px")
.style("top", (eventLocation[1] - 100) + "px");
}
});
d3.selectAll(".country").classed("country-on", false);
d3.select(this).classed("country-on", true);
boxZoom(path.bounds(d), path.centroid(d), 20);
});
Run Code Online (Sandbox Code Playgroud)
现在的问题是,工具提示保持在相对于身体的绝对位置(它停留在屏幕上的确切位置,如果我们平移和缩放地图会产生误导),而我希望工具提示相对于点击的坐标无论我们在地图中缩放还是平移,地图都应该固定到点击的坐标上,类似于这个传单示例(简而言之,我希望工具提示的行为与典型的地图引脚标记类似).
您应该将元素添加到地图的 SVG,而不是主体。像这样:
svg.select("#map")
.append("text")
.data(json)
.classed("geopath", true);
Run Code Online (Sandbox Code Playgroud)