Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often come within larger, more complex projects which makes it challenging to extract just the functionality I need.

The first step is reading in the data:

var data;
function draw(){
    ....
    d3.csv("data/funders.csv", function(err, locations) {
      locations.forEach(function(i){
          addPoint(i['lng'], i['lat'], i['TotalFunding']);
      });
    });
}

To define the svg, I use the following code:

svg = d3.select("#container").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(zoom) // my zoom function
    .on("click", click) // my click function
    .append("g");

g = svg.append("g");

Next, I create a function that appends "g" to the SVG and adds a "gpoint" (geographic point) class to it.

function addPoint(lat, lon, size){

    var gpoint = g.append("g").attr("class", "gpoint");
    var location = projection([lat,lon])
    var x = location[0];
    var y = location[1];

// Here I append 'circle' to the svg.
    gpoint.append("svg:circle")
          .attr("cx", x)
          .attr("cy", y)
          .attr("class","point")
          .style("fill", "blue")
          .attr("r", size/10); //*
}

*The original size information needs to be preserved but scaled accordingly.

To dynamically adjust the circle radius based on the current zoom level, I aim to multiply the size by the zoom scale. A similar approach involving CSS adjustments for country outlines can be applied here:

d3.selectAll(".country").style("stroke-width", 1.5 / scale);

However, implementing this logic for elements within the "gpoint" class poses a challenge that I'm currently exploring.

If needed, additional details can be provided without overwhelming with excessive code.

funders.csv:

funder,lat,lng,TotalFunding
NIH,39.000443,-77.102394,5000
NASA,38.883,-77.0163,1000

Edit

While I managed to adjust circle radii using

g.attr("class", "gpoint").selectAll("circle").attr("r", s)

I'm still figuring out how to access and modify existing circle radii, for instance, through:

g.attr("class", "gpoint").selectAll("circle").data(data).attr("r", function(d){return(d.r*s);}) 

Edit 2

With @kscandrett's assistance, I made progress on this issue.

Preserving the original size was essential. By assigning the funding amount as the dot's ID upon creation, we ensure this data remains intact:

gpoint.append("svg:circle")
//...
.attr("id", Math.sqrt(parseInt(amount) * 0.001))
.attr("r", Math.sqrt(parseInt(amount) * 0.001))
//...

EDIT 3:

A more efficient method involves using datum instead of attr to associate information with each circle:

.datum(Math.sqrt(parseInt(amount) * 0.001))
Further updates involve defining a pointScale function and incorporating it into the move() function for full functionality.

Answer №1

This code snippet demonstrates how to increase the size of circles by 10%

function adjustCircleSize() {
  d3.selectAll('circle').attr('r', function (d, i)
  {
    return d3.select(this).attr('r') * 1.1;
  });
}

Check out this example on CodePen: http://codepen.io/anon/pen/vXRdGx

I utilized data from Jerome Cuckier's blog post as a reference point:

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

Enlarging a JSON structure exported from Clara.IO using Three.js

As a beginner in Three.JS, I have been honing my skills in creating scenes and models. Recently, I imported a washing machine model into my scene and positioned it accordingly. Now, I am trying to scale it up to make it larger, but I am unsure of how to do ...

Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties. let arr = [ { id: 1, name: "tony", hatColor: "blue" }, { id: 2, name: "larry", hatColor: "red" }, { id: 3, name ...

The edges of shapes created with ThreeJs appear to have a fuzzy or blurred outline

Trying to create a cube in ThreeJs using Box Geometry, but encountering strange and shaky lines. Even setting wireframe to false doesn't resolve the issue, as the edges remain problematic. https://i.sstatic.net/sUPAX.png Currently utilizing WebGlRen ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...

retrieving the value of an object key based on changing information

console.log(x, obj.fares) //return undefined output adultFare Object {adultFare: "9.00", childFare: null, seniorCitizenFare: null, disabledFare: null,} How do I retrieve the adultFare value from the object? Is looping through the keys necessary? I expec ...

form_not_submitting_ajax

In the app I'm working on, I have a form that is defined in the following manner: = form_with model: project, remote: true, method: :put do |f| = f.select :selected_draw, options_for_select(project.draws.pluck(:number, :id), draw.id), {}, class: &a ...

What is the best way to modify a newly added element using jQuery?

When a user clicks a button on my screen, a new template is loaded dynamically using jQuery's .load() method. This transition adds new HTML to the page that was not present when the script initially loaded: (function($) { $('.go').on("c ...

When I click the button, I would like the value of the button to be displayed in a textbox

I'm currently working on an interactive virtual keyboard project and need help with a function that will display the pressed button values in a text box located next to the keyboard. Here is the code snippet I've come up with so far: <script ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

Is it possible for PHP to return jQuery code and have it execute immediately upon being echoed?

As someone who is new to jQuery and PHP, I have been tasked by my boss to create a login system for a web page that contains sensitive company information. The challenge is that this webpage consists of just one html/php file. Here is what I have done so ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

I feel overwhelmed and confused by Node, Express, domains, and uncaught exceptions

After hours of research on exception handling in Node, I've come to understand the drawbacks of using uncaughtException. It's clear that shutting down the process can prevent any potential "unknown state" scenarios where anything may happen. The ...

Establishing a dynamic database feature (such as a real-time leader board) on a website

Recently, I designed a fun JavaScript game for my website and now I am contemplating adding a leaderboard feature. However, I am unsure about which type of database would be the best fit - MongoDB, SQLite, or something else entirely. I have heard that SQ ...

Using `v-if` with a Vuex getter

Currently, I am utilizing a vuex getters called isLoggedIn to verify whether a user is logged in or not. <div v-if="isLoggedIn" class="ml-2 py-2 group relative">...</div> data() { return { isLoggedIn: this.$store. ...

The issue with logging out feature

Operating an ASP.NET Web application, I have a Logout feature implemented in JavaScript. However, my current code closes the browser upon Logout, which is not the desired behavior. Instead, I am looking to clear cookies/session and redirect the user to the ...