Rotate the d3.js datamap by dragging using your cursor

Recently, I created a custom map using datamaps developed by @markmarkoh

I'm thrilled with how it turned out, but I am eager to add functionality that allows the map to rotate when dragged with a cursor. My inspiration comes from examples like the ones found here and here.

Below is a snippet of the code I used:

//basic map configuration with custom fills, mercator projection

// JavaScript code here...

<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="http://unilogue.github.io/js/map/datamaps.world.min.js"></script>

<div id="world" style="fill-opacity:0.7; height: 600px; width: 500px; margin-top:-100px;"></div>

After learning about the 'done' callback that enables event usage, I experimented with creating a zoom/pan feature. Now, I'm looking for guidance on implementing d3.behavior.drag and Euler angles to achieve the desired rotation effect.

var map = new Datamap({
                done: function(datamap) {
            // Zoom/pan experimentation code here...
        },

Exploring potential solutions, I stumbled upon a promising example found here. Unfortunately, my attempt to incorporate this method into a 'done' callback didn't yield the expected results. Any suggestions?

    var dragBehaviour = d3.behavior.drag()
    .on('drag', function(){
        // Drag behavior logic here...

        // More JavaScript code continues...
    })

Answer №1

var worldmap;
scope.rotation = [97, -30];

function updateMap() {
  d3.select("#world-map-container").html('');
  initialize();
}// updateMap


function initialize() {
  worldmap = new Datamap({...})

  var drag = d3.behavior.drag().on('drag', function() {
    var dx = d3.event.dx;
    var dy = d3.event.dy;

    var rotation = worldmap.projection.rotate();
    var radius = worldmap.projection.scale();
    var scale = d3.scale.linear().domain([-1 * radius, radius]).range([-90, 90]);
    var degX = scale(dx);
    var degY = scale(dy);
    rotation[0] += degX;
    rotation[1] -= degY;
    if (rotation[1] > 90) rotation[1] = 90;
    if (rotation[1] < -90) rotation[1] = -90;

    if (rotation[0] >= 180) rotation[0] -= 360;
    scope.rotation = rotation;
    updateMap();
  })

 d3.select("#world-map-container").select("svg").call(drag);

}// initialize

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

I specified Authorization Bearer in the Fetch API configuration, however, the Request Headers do not contain the necessary Authorization information

Check out the following code snippet: fetch('http://localhost:3000/tasks/', { method: 'GET', mode: 'no-cors', headers: new Headers({ 'Authorization': 'Bearer <jwt_token>' ...

What is the method to invoke a function within a factory in angularjs by using a string parameter?

I have a complex logic that I want to encapsulate in an AngularJS factory for easy use with dependency injection. The challenge is that the logic is dynamic, so I don't know in advance what functions will be available. What I have is a string represen ...

A sophisticated method for dynamically expanding a text input field as characters are being typed

I recently came across a tutorial on how to make input type text auto-expand while also setting a specific width expand, which I found quite helpful. However, upon implementation, I noticed a few issues that need to be addressed: When typing in capital l ...

Escaping an equal sign in JavaScript when using PHP

I am currently working on the following code snippet: print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><input type='button' val ...

Creating JOIN tables within the create action involves assigning related ids to each table

I am currently working on a room reservation system that involves including options for each room. Data related to the options and their join table, reservation_options, are successfully inserted into the params. However, I am facing an issue with assignin ...

Methods for altering the color of a div using addEventListener

Why doesn't the color change when I click on the div with the class "round"? Also, how can I implement a color change onclick? var round = document.querySelector(".round"); round.addEventListener("click", function() { round.style.backgroundCol ...

A guide to simultaneously sending dual variables by implementing Ajax via JavaScript

I am currently facing an issue with a textarea and PHP variables. I have created a script as shown below: $(document).ready(function(){ $('.post').keyup(function(e){ var post = $.trim($('.post').val()); if (post != ...

Combining Various Data Types in a Flexible List

I'm looking for a way to dynamically add rows to a table. Right now, I have the input type on the server (whether it's int, bool, string, etc), but I want to know how to implement a field accept combobox. Here is the code in cshtml: <tr ng-r ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

What is the best way to get rid of trailing numbers in material UI class names?

The standard class for the material ui input box is .MuiInputBase-input, but when I inspect it using developer tools, I see that the same class is displayed as .MuiInputBase-input-619. How can I remove the suffix from the class name? I am currently utili ...

Child component in VueJs is undergoing a situation where the variable is found to be

Whenever an event is triggered, a function is called to populate a variable and open a modal from a child component. However, in the modal, the new variable appears empty initially. If I close and then reopen the modal, the data finally loads. I have atte ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Error Alert - Troubleshooting AJAX JSON Parsing Issue

I've encountered a problem with AJAX that involves parsing a JSON Array from a webservice I am developing. The front-end of my project uses a simple combination of ajax and jQuery to showcase the results retrieved from the webservice. Despite being c ...

Guide on retrieving a file through an HTTP request with restricted cross-origin access restrictions

Having some issues with downloading files from specific links, such as . My goal is to automate the download process for these redirected files. The challenge I'm facing is that trying to access the link directly through a web browser just gives me a ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

Limit the selection to just one element in a v-for loop in VueJS

I am utilizing Vue v2 My goal is to change only the properties of the selected element. Specifically, when the response is marked after clicking, it should switch to red color with a text that reads 'Unmark'. Conversely, if the button is clicked ...

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...