How to Fill this type of Array in Javascript..
var neighborhoods = [
{lat: 52.511, lng: 13.447},
{lat: 52.549, lng: 13.422},
{lat: 52.497, lng: 13.396},
{lat: 52.517, lng: 13.394}
];
I have tried this way but its not happening
$.each(result.geoloc, function(index,geoloc) {
geoloc_split=geoloc.Geoloc.split(',');
// alert(geoloc_split[0]+","+geoloc_split[1]);
var lat="lat: "+geoloc_split[0];
var lng = "lng: "+geoloc_split[1];
neighborhoods.push(lat,lng);
geoloc_split="";
});
Zoe - Save the data dump
28.4k22 gold badges130 silver badges164 bronze badges
2 Answers 2
You are pushing only values to array. You need to push new object (e.g. create it with object literal). Furthermore you need to convert string values to float:
var lat = parseFloat(geoloc_split[0]);
var lng = parseFloat(geoloc_split[1]);
neighborhoods.push({
lat: lat,
lng: lng
});
In ES6 you can use property value shorthand:
neighborhoods.push({lat, lng});
answered Feb 27, 2016 at 11:13
madox2
52.3k21 gold badges106 silver badges101 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Manish
Its giving me error InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
You should do like this :
$.each(result.geoloc, function(index,geoloc) {
geoloc_split=geoloc.Geoloc.split(',');
neighborhoods.push({
lat:parseFloat(geoloc_split[0]),
lng:parseFloat(geoloc_split[1])
});
geoloc_split="";
});
Because your neighborhood array is an array of object you need to fill it with objects .
4 Comments
Manish
Its giving me Error InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
Manish
Thanks @Marox Tn, But I am Still getting the same Error I have also alerted the values of geolocations, they are as expected but still :(
Marox Tn
What do you get from
console.log(geoloc) inside the $.each ?Manish
Object {Geoloc: "-38.1024466,145.1700861"} showmap:175 Object {Geoloc: "-37.9996694,145.1121534"} showmap:175 Object {Geoloc: "-37.9957947,145.1101839"} showmap:175 Object {Geoloc: "-38.0030245,145.1184165"} showmap:175 Object {Geoloc: "-38.0030245,145.1184165"} showmap:175 Object {Geoloc: "-37.8176861,144.8396454"}
lang-js