JSON is the way to put the output in, that ensures that the result will be valid JavaScript and protects you from arbitrary code execution in JS.
var coordinatesArray = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
$rows = $wpdb->get_results($sql);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '[]';
}
?>;
for (var i=0; i<coordinatesArray; i++) {
alert(coordinatesArray[i].id);
alert(coordinatesArray[i].lat);
alert(coordinatesArray[i]["long"]);
}
The other way would be creating a JS object with the id field as key of the JS object:
var coordinatesMap = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
// note: OBJECT_K, the result will be an associative array with the first field of a
// row as key
$rows = $wpdb->get_results($sql, OBJECT_K);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '{}';
}
?>;
for (var id in coordinatesMap) {
if (coordinatesMap.hasOwnProperty(id)) {
alert(id);
alert(coordinatesMap[id].lat);
alert(coordinatesMap[id]["long"]);
}
}
Please replace alert by something else, it's not really user-friendly. Remember that PHP != JavaScript and you cannot use PHP functions in JavaScript and vice versa. If you're not sure how the output would look like, use the View source option of a page.
References: