Extracting information from a singular geojson file amidst a collection of multiple geojson files

I am currently working with multiple geojson layers and overlaying them using groups in my project. To center the map on a specific geojson file, I referred to Mike's helpful answer available here -> Center a map in d3 given a geoJSON object

The issue I'm facing, which I suspect is due to JavaScript's asynchronous nature, is that when I define the projection on a large geojson file, other geojson features fail to project correctly.

How can I appropriately translate and scale the map within this system? Are there better approaches to tackle this problem?

EDIT

I've come up with a temporary solution, however, it restricts me from changing the projection programmatically. Using the debugger, I extracted values for s and t, then hard-coded those values at the beginning of the script after defining the projection, before calling any geojson functions.

Below is the snippet of my code:

var width = 1100,
    height = 850;

var projection = d3.geo.mercator();

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var landGroup = svg.append("g"),
    waterGroup = svg.append("g"),
    urbanGroup = svg.append("g"),
    borderGroup = svg.append("g");

d3.json("geoData/naLand.geojson", function(land) {

    projection
        .scale(1)
        .translate([0,0]);
    
    var b = path.bounds(land),
        s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
        t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
    
    projection
        .scale(s)
        .translate(t);

    landGroup.selectAll("path")
        .data(land.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("fill", "#888888")
        .attr("stroke", "#111111")              
})

d3.json("geoData/naWater.geojson", function(water) {

    waterGroup.selectAll("path")
        .data(water.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("fill", "#C9DBFF")
        .attr("stroke", "#0066FF")
        
})

d3.json("geoData/PNW_Municipalities.geojson", function(urban) {

    urbanGroup.selectAll("path")
        .data(urban.features)
        .append("path")
        .attr("d", path)
        .attr("fill", "#666666")
        .attr("stroke", "#666666")  
        
})

d3.json("geoData/CanadianBorder.geojson", function(border) {
        
    borderGroup.selectAll("path") 
        .data(border.features) 
        .enter() 
        .append("path") 
        .attr("d", path) 
        .attr("stroke", "#555555")
        .attr("stroke-width", "3")
        .attr("stroke-dasharray", "2,2")
        .attr("fill", "transparent")                
})

Answer №1

If you want to streamline the loading of multiple JSON files before taking any action, consider using queue.js. This allows you to load all the necessary data and then proceed with your projections.

Here's an example implementation:

queue()
    .defer(d3.json, 'data/countries.geojson')//loading country data
    .defer(d3.json, 'data/cities.geojson')//loading city data
    .await(createMap);

function createMap(error, countries, cities) {
//create your map here
}

Check out a live demo here.

I hope this information proves useful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a raycasting technique in conjunction with the camera to achieve a dynamic crosshair effect reminiscent of Google Cardboard

I'm looking for a way to implement the Google Cardboard crosshair effect in my three.js scene. Essentially, I want to create a dot or crosshair in the center of the screen for VR navigation. How can I achieve this and use a raycaster to interact with ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

Utilizing JSON in D3.js

Is there a way to create a pie chart or bar chart in d3js using JSON data similar to this example? {"ratings": {"2": 1, "3": 3, "4": 12, "1": 8, "5": 33} } Or like this example: {"languages": {"1": 35, "2": 22}} I would greatly appreciate any assistanc ...

Encountered an issue while executing an npm script using Yarn: "ERR spawn EINVAL"

Encountering a puzzling error while attempting to execute an npm script involving Yarn. Here's what happened: Started a project with create-react-app. Added the specified script to my package.json file. "scripts": { "lint": & ...

Display only the background image or color behind a stationary element

Our website features a header with a fixed position that remains at the top of the page while scrolling. The product team has requested a gap or margin between this fixed element and the top navbar. However, when we implemented this gap, users started not ...

The concept of nested conditionals occurs when one

Struggling to dynamically assign a variable value based on viewport size using Hooks in Gatsby. While nested conditionals seem to work initially, resizing the browser window manually triggers an error: Rendered fewer hooks than expected. This may be caus ...

Tips for spanning a div to fill 100% of the available width

I am facing an issue with two sibling divs nested inside a parent div as shown below: <div class="row filters-box"> <div class='col-md-1'> <div class="title"><label class="filter-title">Filter</label>< ...

Exploring the benefits of utilizing TypeScript's async await feature within the Node

I've encountered a challenge trying to accomplish the following tasks simultaneously: Developing in Node.js Coding in TypeScript Implementing async await Facilitating debugging Background: In my TypeScript-based Node.js project, I am incorporating ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

Is it possible to incorporate Nth child into JavaScript?

Is it feasible to implement an Nth Child in the following code snippet? $(function() { var count = $(".parent a").length; $(".parent div").width(function(){ return ($(".parent").width()/count)-5; }).css("margin-right","5px"); }); ...

Updating Span or Div content by ID using Jquery and Ajax without needing to reload the page

Here is the code snippet I am working with: <span class='numberofthings' id='123456'> Things: ".$things."</span> Along with the following JavaScript / Ajax code: function click(obj) { $.ajax({ var id = 123456 ...

Adding a regional iteration of a library that was unable to be loaded

Recently, I have been experimenting with PhantomJS to capture screenshots of a webpage every five minutes. While the process runs smoothly most of the time, I encountered an issue where the AngularJS library fails to load intermittently. This results in th ...

Click the button to trigger the pop-up

After creating a photo gallery using a plugin, my goal is to display this gallery when the user clicks on my homepage button. I am unsure how to make this happen and would appreciate any assistance. Below is my button code: <div class="ow-button-base ...

Remove any repeated elements from the array and ensure that the element which occurs the most is placed at the beginning of the new array

Given an array "source" with values [2, 9, 9, 1, 6], we use the filter method to remove duplicate elements. The variable 'ans' stores the result. Now, how can we rearrange the elements in such a way that the highest repeated value (9) comes firs ...

Tips on how to efficiently wrap content within a column layout, and to seamlessly shrink it if necessary

I recently encountered an issue where I am attempting to create a three-column layout with each column filled with a dynamic number of divs (boxes) ranging from 5 to 15, each with its own height based on its content. These divs are expected to: 1) Be dis ...

Is it possible to send information via the URL while using jQuery Mobile?

My mobile application utilizes an in-app browser to send information, such as deviceID, to my server via a URL. For instance, the browser opens a web-page (jquery Mobile): www.myserver.com/doWork.html#deviceID Within the doWork.html file on the server si ...

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

sequencing the compilation of Node.js modules

I am facing an issue with my node application involving multiple interdependent modules exported using module.exports. These modules include mongohelper, transaction, server, conhandlr, and appmin. Compile order- mongohelper transaction server (..the ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...