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

Converting a JSON array to C# and vice versa in Xamarin Forms

I've been struggling to send a C# object as JSON array to an API endpoint. I feel like I'm going crazy trying to solve these issues. Here's a sample of the JSON data: Array ( [user_id] => 0002323445635 [order] => {"order":{" ...

Learn how to easily insert a marker on a map using leaflet js in vue 3 with just a simple click

Hey everyone! I need some help with a challenge I'm facing. I can't seem to get click coordinates to create a new Marker on my map. Check out the image here And another image here ...

What could be preventing the onclick event from functioning properly in JavaScript?

After creating a basic JavaScript code to practice Event handling, I encountered an issue where the function hello() does not execute when clicking on the "Click" button. What could be causing this problem? html file: <!DOCTYPE html> <html> ...

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

Implement a counter in a JavaScript table, initializing it to zero

I have successfully written my code, but there is one issue. The first row is starting with the number one instead of zero. I'm looking for suggestions on how to start from zero. Any help would be greatly appreciated. Thanks! <script> var tabl ...

Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post d ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: Is there a way to hide them from being easily accessible? And most importantly, is it s ...

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

Pushing state history causes browser back and forward button failure

I'm currently utilizing jQuery to dynamically load content within a div container. On the server side, the code is set up to detect if the request is being made through AJAX or GET. In order to ensure that the browser's back and forward buttons ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Component built in ReactJS for file uploads to a server running on Spring MVC/Data-REST

For quite some time, I have been on the lookout for a ReactJS component that enables file uploading from a browser, with the ability to save it to the server where the ReactJS application is deployed. I've come across several components that facilita ...

How to Troubleshoot jQuery AJAX Not Sending JSON Data

I've been attempting to make an ajax request, but it keeps returning with an error response. $('form#contactForm button.submit').click(function () { var contactName = $('#contactForm #contactName').val(); ...

File bootstrap.min.css is currently experiencing compatibility issues

I am currently working on a website where I have two images that are displaying vertically. However, I would like these images to be displayed horizontally with animation. I attempted to use Bootstrap to achieve this horizontal layout, but when I include ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

The Angular project failed to run properly following the ng build command

Just started working with Angularjs 2 and encountered an issue after running ng build. The compiled files were placed in the dist folder, but when I checked the index.html file within that folder, all the scripts had missing references even though they w ...

Unable to include query parameters in the nextjs dynamic route

I have a file called [slug].js. What I am attempting to do is add a query parameter to this dynamic route. Here's the code: await router.replace({ pathname: `${router.pathname}`, query: { coupon }, }, undefined, ...

Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object. The API requires the data to be structured like this: "data": [ { "id": 1, "nombre": "AGUASBLANCAS-AGB&qu ...