Create a d3 map specifically for a selected region based on the provided latitude and longitude coordinates

I am currently working on developing a d3 map inspired by the codepen created by Andy Barefoot: https://codepen.io/nb123456/pen/zLdqvM?editors=0010. My goal is to adjust the initiateZoom() function in a way that setting specific lat/lon coordinates for a box around Ohio will result in the map panning over Ohio upon initialization.

function initiateZoom() {
  minZoom = Math.max($("#map-holder").width() / w, $("#map-holder").height() / h);
  maxZoom = 20 * minZoom;

  zoom
    .scaleExtent([minZoom, maxZoom])
    .translateExtent([[0, 0], [w, h]])
  ;

  midX = ($("#map-holder").width() - minZoom * w) / 2;
  midY = ($("#map-holder").height() - minZoom * h) / 2;//Original values
  var swlat = 32;
  var swlon = -82;
  var nelat = 42;
  var nelon = -72;
  var projectCoordinates = projection([(swlat+nelat)/2, (swlon+nelon)/2]);

  /*This did not work
  var midX =  minZoom*(w-(swlat+nelat)/2) - ($("#map-holder").width()-(swlat+nelat)/2);
  var midY = minZoom*(h-(swlon+nelon)/2) - ($("#map-holder").height()-(swlon+nelon)/2);*/
  /*Neither did this
  var midX = minZoom*(w-projectCoordinates[0])-($("#map-holder").width()-projectCoordinates[0]);
  var midY = minZoom*(h-projectCoordinates[1])-($("#map-holder").height()-projectCoordinates[1]);*/

  svg.call(zoom.transform, d3.zoomIdentity.translate(midX, midY).scale(minZoom));
}  

The initial concept was:

1: Obtain the current pixel display of the map
2: Calculate the new pixel distance from the corner of the map to the specified point after zooming 
3: Determine the pixel distance from the center of the container to the top
4: Subtract the values obtained from steps 2 and 3

The original intention was to shift the map so that it initializes with zoom and pan centered over the map. I attempted to modify this process initially by directly applying the lat/lon values into the equations provided above. Additionally, I tried transforming the lat/lon values using projections before substituting them in, but encountered difficulties. Can you guide me on what needs to be done to achieve the desired outcome?

Answer №1

Avoiding the use of translateExtent can be preferred because it's influenced by the current zoom level.

Instead, consider implementing the following method:

function initializeZoom() {
  // Calculate the minimum zoom level to prevent empty space around "Countries"
  minZoom = Math.max($("#map-holder").width() / w, $("#map-holder").height() / h);
  
  // Set the maximum zoom as a multiple of the minimum zoom
  maxZoom = 20 * minZoom;
  
  // Define the zoom extent based on chosen values
  // Adjust translate extent to confine map movement within viewport boundaries
  zoom
    .scaleExtent([minZoom, maxZoom])
    .translateExtent([[0, 0], [w, h]])
  ;

  var swlat = 33;
  var swlon = -83;
  var nelat = 43;
  var nelon = -73;
  var nwXY = projection([swlon, nelat]);
  var seXY = projection([nelon, swlat]);
  var zoomScale = Math.min($("#map-holder").width()/(seXY[0]-nwXY[0]), $("#map-holder").height()/(seXY[1]-nwXY[1]))
  var projectCoordinates = projection([(swlon+nelon)/2, (swlat+nelat)/2]);

  svg.call(zoom.transform, d3.zoomIdentity.translate($("#map-holder").width()*0.5-zoomScale*projectCoordinates[0], $("#map-holder").height()*0.5-zoomScale*projectCoordinates[1]).scale(zoomScale));
}

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

Retrieving data from getServerSideProps and utilizing it inside Layout component in Next.js

Currently, I am in the process of developing a web application with Next.js. This project involves creating an admin dashboard that will be utilized to manage various tasks, each with its own SSR page. DashboardLayout : export const DashboardLayout = ({ch ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

The issue with the Marquee function in Firefox persists, despite my efforts to incorporate several jQuery plugins

Currently in the process of developing a website, I have incorporated various jQuery scripts for enhanced functionality, such as parallax effects: jquery.parallax.js jquery.anythingslider.fx.js jquery.anythingslider.js As the development progresses, ...

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...

The process of automating e-signature input with Selenium

Is there a way to automate e-signature input in Selenium? I attempted using the action class to draw a line on the canvas object. Below is the code I used: Actions actionBuilder=new Actions(driver); Action drawOnCanvas=actionBuilder ...

Painting issue on Chrome and Opera browsers

I've discovered a strange issue with my page rendering in blink browsers where it paints and then suddenly "unpaints." Once the page has loaded, most of the viewport becomes blank and stops painting. Here is how the screen should look after I manually ...

Internet Explorer failing to trigger Ajax requests

I'm encountering an issue with my script on my webpage - it works perfectly in Chrome, but Internet Explorer is not entering the success{} function of Ajax. It does go into the Complete{} function without any problems. I attempted to pass the data var ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Navigate to items within a content block with a set height

I have a <div> that has a fixed height and overflow-y: scroll. Inside this div, there is mostly a <p> tag containing a long text with some highlighting (spans with background-color and a numbered id attribute). Just to note, this is an HTML5 a ...

Using jquery, transform json data into html table format

As a beginner in the realm of coding, I am currently experimenting with extracting data from my json file and transforming it into an HTML table. My tool of choice is the Atom code editor, and I am attempting to use JavaScript, specifically jQuery, to it ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

Issue with Zeroclipboard not copying content when initially clicked

My code is experiencing some issues where it doesn't work on the first click, but strangely works on the second click. $("#btnCopiar").on("click",function(){ var clipBoardObj = new ZeroClipboard($("#btnCopiar"), { moviePath: ".. ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

"Utilizing Jest Globals to Provide an Empty Input for a Function: A Step-by-

I have developed a function that outputs null when the input is empty: const testFunc = (param) => { if (param) { //blabla } return null; }; To verify the return null behavior with an empty param, I want to utilize describe...it...: describe( ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Warning thrown when Ajax call is executed within a function, causing it to break

I'm in the process of refactoring a JavaScript file that performs multiple ajax calls. I have a function that makes an ajax call, retrieves an object with details required for other ajax calls. const makeCall = (url, type, data, done) => { $.aj ...

JavaScript code can be used to access data from a JSON file and present the flower and color information in separate unordered lists

How can I retrieve data from a JSON file in JavaScript and display flowers and colors in separate unordered lists? I am having trouble adding it. fetch('dataFiles/midterm.json', { method: 'GET', mode: 'no-cors' ...