Showing off map positions on D3 using data from a JSON array

I have received a JSON response containing coordinates from PHP in the following format:

{"All":[{"longitude":"36.8948669","name":" Manyanja Rd, Nairobi, Kenya","latitude":"-1.2890965","userID":"1"}, ...]}

Next, I am processing it using JavaScript as shown below:

$.ajax({
url : "http://xxx.xxx.xxx/GetLocations.php",
dataType : "json",
data :"",

success : 
function (data){
//populate map is the function that gets the coordinates for display using d3
 //When I console.log(data), the JSON data is displayed meaning the data is present

populate_map(data)
}
});

This is the populate_map function.

function populate_map(pos_data){
    console.log(pos_data.All[0]);
    var width = 700;
var height = 580;

var svg = d3.select( "body" )
    .append( "svg" )
    .attr( "width", width )
    .attr( "height", height );

var g = svg.append( "g" );

var albersProjection = d3.geo.albers()
    .scale( 190000 )
    .rotate( [71.057,0] )
    .center( [0, 42.313] )
    .translate( [width/2,height/2] );

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

var projection = d3.geo.mercator()
.center([36.8, -1.3])
.scale([60000])
.translate([width/2, height/2]);

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

g.selectAll( "path" )
    .data( data.geometries )
    .enter()
    .append( "path" )
    .attr( "fill", "#ccc" )
    .attr( "stroke", "#333")
    .attr( "d", nairobipathing );

      svg.selectAll("circles.points")
        .data(pos_data)
        .enter()
        .append("circle")
        .attr("r",5)
        .attr("transform", function(d) {return "translate("  d.All.longitude+","+d.All.latitude ")";});
}

The issue lies in the fact that no coordinates are being displayed on the initialized Nairobi map. However, when I log the data in the populate function, the JSON data is visible.

The last SVG element is supposed to show these coordinates on the map but it doesn't seem to be working and no coordinates are displayed.

I would appreciate any assistance in identifying where the problem might be occurring.

Answer №1

One thing to note is that you are currently using two different projections, which may cause confusion. It would be more straightforward if you eliminate any mentions of the Albers projection, as it is centered in the Atlantic Ocean off the coast of North America.

Another suggestion is to pass an array of points within the data object instead of passing the entire data object itself.

Furthermore, make sure that the values used in the transform function are in SVG coordinate space rather than geographic coordinate space. In your code snippet, you are referencing d.All.longitude and d.All.longitude without applying the necessary projection. You should use projection([longitude, latitude]) to obtain the SVG coordinates for the circle, returning a coordinate [x,y] in the SVG coordinate space.

Considering the above points, you could modify your code by appending something like this:

     svg.selectAll(".points")
            .data(pos_data.All)
            .enter()
            .append("circle")
            .attr("class","points")
            .attr("r", 5 )
            .attr("stroke","orange")
            .attr("transform", function(d) {return "translate(" + projection([d.longitude,d.latitude]) + ")";})

Alternatively, you can also use .attr("cx", x) or .attr("cy", y) to specify the point's center instead of using translate:

         svg.selectAll(".points")
            .data(test.All)
            .enter()
            .append("circle")
            .attr("class","points")
            .attr("r", 5 )
            .attr("stroke","orange")
            .attr("cx", function(d) { return projection([d.longitude,d.latitude])[0]; })
            .attr("cy", function(d) { return projection([d.longitude,d.latitude])[1]; })

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

Assign the variable of one function to another function

I have a collection of buttons with usernames as values (such as jason, chan, brad, etc.). When a user clicks on a button, it is moved to a specific div. For example: <input type="button" onClick="nano();" id="name1" class="names" name="jason" value=" ...

Content is missing from the response of the AngularJS $http request

Attempting to retrieve content from a website using Angular's $http service. The request seems to be successful as console.log(response.data) displays most of the content but is missing some parts. Check out my code below: $http = angular.element(doc ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Toggle Canvas Visibility with Radio Button

As I immerse myself in learning Javascript and Canvas, the plethora of resources available has left me feeling a bit overwhelmed. Currently, I am working on a dress customization project using Canvas. // Here is a snippet of my HTML code <input type=" ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Transmit information from a JavaScript AJAX function to a JSP page

My current goal involves a user clicking on a link on the home page, let's say /home.jsp. Upon clicking this link, I extract the value and use it to call a RESTful resource that interacts with a database and returns a response. The communication with ...

Saving a form with repeater fields using Ajax

I created a dynamic form in HTML that allows users to add multiple members as needed. The member details are stored within a div like this: <div class="form-group form-group-100 clearfix"> <label>Name:</label> <input type="te ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...

"Trouble with Heroku: JavaScript script failing to load with 404

My adventure in building my first web app using MEAN on Heroku has been both thrilling and frustrating. I meticulously followed their guide to set up a sample app, downloaded the code, and made modifications to have a customized login page. However, I hit ...

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

Mixing strings with missing slashes in links

console.log(mylink) When using the console to log mylink, the expected result is a normal link like http://example.com/something.jpg. I tried concatenating it as shown below: var html = '<div id="head" style="background:linear-gradient(rgba(0, 0 ...

What is the most effective way to compare a property with the values stored in an array of objects?

d : {"children":[{"name":"China","children":[{"name":"China","value":400,"percentage":"33.33"}],"index":0},{"name":"England","children":[{"name":"England","value":300,"percentage":"33.33"}],"index":1},{"name":"Malaysia","children":[{"name":"Malaysia","val ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

Encountered a 500 (Internal Server Error) when attempting to access a webservice using jQuery for an

Whenever I try to access the autosuggest webservice from the script, an internal server (500) error occurs. ERROR: POST localhost:4202/Presentation/AutoCompleteService.asmx/GetAutoCompleteData 500 (Internal Server Error) jquery.min.js:130 Seeking assistan ...

Using PlayFramework: How to implement Ajax, Drag and Drop functionality, and File Upload with File object in the controller?

Is there a method to upload a file through Ajax and drag-and-drop from the desktop while also supporting PlayFramework's capability to convert file uploads into a File object? I have experimented with multiple approaches, but none seem to be function ...

Inverting the hierarchy of a tree structure

I am currently working with a tree structure and utilizing the jstree jQuery plugin. My main objective is to reverse the structure. The desired structure should resemble the one shown in this image. I have made modifications using MS Word, so it does not ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

Issue encountered when trying to import an image URL as a background in CSS using Webpack

I have been trying to add a background image to my section in my SCSS file. The linear gradient is meant to darken the image, and I'm confident that the URL is correct. background-image: url(../../assets/img/hero-bg.jpg), linear-gradient(r ...