After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet:
navigator.geolocation.getCurrentPosition(function(position) {
let coordinates: [number, number] = [position.coords.longitude, position.coords.latitude]
}
// e.g. [-70.1234567, 40.987654]
The function to retrieve county information using D3 is as follows:
getGeoLocation(topology, coordinates) {
topojson.feature(topology, topology["objects"]["counties"])["features"].filter(function(polygon) {
polygon["geometry"]["coordinates"].forEach(coord => {
console.log(d3.polygonContains(coord, coordinates))
})
})
}
Despite implementing this function, it consistently returns false
for every county object. There seems to be some confusion whether to use d3.geoContains()
or d3.polygonContains()
, especially when dealing with MultiPolygon
features in the provided TopoJSON file (link here: ).
Any suggestions on how to address this issue?
UPDATE
Could the problem lie in the lack of projection within the geoPath()
used on the TopoJSON data? Even without projection, the comparison with basic JSON does not resolve the issue...
Provided below is some additional context about the map (developed in Angular with TypeScript), where this.topology
refers to the imported JSON from the specified URL:
path: any = d3.geoPath()
this.svg = d3.select("#map")
.attr("preserveAspectRatio", "xMidYMid meet")
.attr("viewBox", "0 0 975 610")
.attr("height", "100%")
.attr("width", "100%")
this.g = this.svg.append("g")
.attr("id", "g")
this.counties = this.g.append("g")
.selectAll("path")
.data(topojson.feature(this.topology, this.topology["objects"]["counties"])["features"])
.join("path")
.attr("d", this.path)
.attr("class", "county")
.attr("id", function(d) {return d["id"]})