D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following:

https://i.sstatic.net/1brVx.png

However, when I create the map with D3/topoJSON, it shows up small and inverted.

https://i.sstatic.net/LgQBd.png

Even after exploring various solutions (like Center a map in d3 given a geoJSON object), adjusting the projection does not seem to have any effect on the generated map regardless of changing the scale, adding a translate, or rotating it.

I obtained the shapefile from here: and converted it to topoJSON using mapshaper.

Any suggestions?

A demo can be accessed here: http://jsfiddle.net/r10qhpca/

var margin = {top: 60, right: 40, bottom: 125, left: 100},
      containerWidth = $('.events-section1-graph').width(),
      containerHeight = $('#events .section1').height();  

  var width = containerWidth - margin.left - margin.right,
      height = containerHeight - margin.top - margin.bottom;

  var xScale = d3.scale.linear()
                 .range( [0, width] ),
      yScale = d3.scale.linear()
                 .range( [height, 0] );

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

  var projection = d3.geo.mercator()
                     .scale(5000000)
                     .translate([width / 2, height / 2])
                     .rotate([0, 0, 180]);


  var svg = d3.select('.events-section1-graph')
              .append('svg')
              .attr('width', width + margin.left + margin.right)
              .attr('height', height + margin.top + margin.bottom)
              .append('g')
              .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

  queue().defer(d3.json, 'js/continent.json')
         .await(ready);

  function ready(err, world) {
    if (err) console.warn("Error", err);

    var tj = topojson.feature(world, world.objects.continent);

    var continent = svg.selectAll('.continent-path')
                       .data(tj.features)
                       .enter()
                       .append('path')
                       .attr('class', 'continent-path')
                       .attr('d', path);

Answer №1

The issue is located right here:

  var path = d3.geo.path()
    .projection(projection);//at this point, projection is undefined
  var projection = d3.geo.mercator()
    .scale(width)
    .translate([width / 2, height / 2]);

The problem arises because you are defining the projection later and then assigning it to path. This results in an undefined value being stored in the projection for the path.

The solution is straightforward:

  //let's first create the projection  
  var projection = d3.geo.mercator()
    .scale(width)
    .translate([width / 2, height / 2]);
  //then we assign the projection to the path
  var path = d3.geo.path()
    .projection(projection);

Functional code can be found here.

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

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Utilizing Font Awesome icons dynamically presents challenges when integrating with SVG & JavaScript

Recently, I started using the new JS&SVG implementation of font-awesome's v5 icons. It seems to be working perfectly for icons (such as <i class='fas fa-home'></i>) that are already present in the DOM at page load. The <i& ...

Setting up bootstrap for PHP: A step-by-step guide

Struggling with integrating PHP and Bootstrap? I recently attempted to do the same, but unfortunately, my website doesn't seem to recognize Bootstrap. Instead of the sleek Bootstrap design, it's displaying a simple HTML layout. Here's a snip ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

Modify the arrow design for the expansion panel's default arrow style

Looking to customize the design of an angular expansion panel? Check out the images below for inspiration: Before Customization: https://i.sstatic.net/4u6NS.png After Customization (Not expanded): https://i.sstatic.net/8N6Br.png After Customization (E ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

What is the true appearance of Ajax?

After spending a few days researching Ajax to use with the Django Python framework, I came across numerous resources on the topic. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyStat ...

Is it true that all events in JavaScript go through capturing and bubbling phases?

My current project involves binding one eventListener to an <audio> element for the play event and another eventListener to its parent element for the same event. I've observed that the callback for the child element always gets executed, while ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

An error occurred - 0x800a1391 - JavaScript runtime error: The function 'SelectAllCheckBoxes' has not been defined

I'm currently in the process of learning web development and I am trying to incorporate jQuery into my ASP .NET page. Within the header section, I have included the necessary references: <head id="Head1" runat="server"> <link href=" ...

Using Slick Slider and Bootstrap CSS to display text on top of images

Currently, I am utilizing the slick slider from and I want to overlay text on top of the image. I tried using bootstrap carousel-caption, which works well with any image. However, with slick slider, it seems like the text is not at the highest level as I ...

How can we capture and execute a function on the server in Next.js in response to a user's request for the index page (/)?

Is it possible to use a middleware function or another method in Next.js to check if a user is trying to access the home page? My goal is to intervene when a user tries to reach the home page. Intercepting a URL request is quite straightforward with Next. ...

Error: Unable to access the 'name' property of an undefined value. Despite my efforts, I am unable to determine the root cause of this issue. My technology stack includes mysql for the database, nodejs for the backend,

Can someone help me with a TypeError: Cannot read property 'name' of undefined error I'm encountering while trying to add new users to a MySql database using Node.js and EJS as the view engine? I've been unable to identify the cause of ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Align two containers centrally using absolute positioning inside a division

I am looking for a way to centrally align two "boxes" within a div using CSS. These boxes are positioned absolutely. For reference, here is the JSFiddle link: http://jsfiddle.net/p4sA3/8/ Is there a method to achieve this alignment without specifying spe ...

Why does the <select> dropdown flash when I select it?

Currently utilizing Angular 1.3 and Bootstrap 3.3.x CSS without the JS functionality. There is also an interesting animated GIF embedded within. <div class="form-group"> <div class="col-lg-3"> <label clas ...

What is the best way to customize a div depending on the validation status of all reactive form fields within it?

I am facing a challenge with a rather complex form that contains multiple fields. Some of these fields are used to create logical blocks, and I would like to emphasize the surrounding div if any of these included fields are invalid. Can you suggest the bes ...