I have a collection of data like this –
[
0: {latitude: "0", longitude: "0", user_country_name: "-", user_country_code: "-", total_visitors: 4}
1: {latitude: "-33.867851", longitude: "151.207321", user_country_name: "Australia", user_country_code: "AU", total_visitors: 1}
2: {latitude: "-23.960831", longitude: "-46.333611", user_country_name: "Brazil", user_country_code: "BR", total_visitors: 1}
3: {latitude: "45.411171", longitude: "-113.468712", user_country_name: "Canada", user_country_code: "CA", total_visitors: 2}
4: {latitude: "47.366669", longitude: "8.55", user_country_name: "Switzerland", user_country_code: "CH", total_visitors: 1}
]
I get the result by using
var location_data = [];
$.ajax({
type: "GET",
url: url,
data: data,
success: function(data)
{
var obj = JSON.parse(data);
console.log(obj)
obj.forEach(function(item) {
var data = { latLng: [parseFloat(item.latitude), parseFloat(item.longitude)], name: item.user_country_name }
location_data.push(data);
})
}
});
console.log(location_data)
Output : Something like this
[
0: {latLng: Array(2), name: "-"}
1: {latLng: Array(2), name: "Australia"}
2: {latLng: Array(2), name: "Brazil"}
3: {latLng: Array(2), name: "Canada"}
4: {latLng: Array(2), name: "Switzerland"}
]
But I want something like the following, I mean display the item of the object like [-33.867851, 151.207321] not as array(2);
Expected Output:
[
0: {latLng: [0,0], name: "-"}
1: {latLng: [-33.867851, 151.207321], name: "Australia"}
2: {latLng: [-23.960831, -46.333611], name: "Brazil"}
3: {latLng: [45.411171, -113.468712], name: "Canada"}
4: {latLng: [47.366669, 8.55], name: "Switzerland"}
]
2
Answers
The input data itself has the latitudes/longitudes as string, not number. Strings are any kind of text, wrapped around "" quotes, as in your input data. You need to convert it to a number. For us humans, "-33.867851" and -33.867851 are the same intuitively. But for computers they are completely different things: one is text and one is number, regardless of there is a number as the text (it could be anything).
You can either:
parseFloat
in your foreach where you set data, e.g.latLng: [parseFloat(item.latitude), parseFloat(item.longitude)]
to convert string representation of the number into an actual number.I think the issue is that in the line where you set the data.
You are creating an array which results in the printout being
array(2)
The solution is to add single or double quoutes to that line. there is also no need to parse the data since it is already a string.