SnowmanPusha February 2016

Google Maps Api using Math.random to get random location - JS

I am having trouble getting my map to go to a random location. I want it to go to a random location between the bounds (lat -85 to 85, lng -180 to 180). Whenever the button is clicked the function makes the map grey.

function random(lat, lng){
var random = new google.maps.LatLng((Math.random()-85)*85+, (Math.random()-180)*180));
map.panTo(random);
}

Answers


Giuseppe Orrù February 2016

var random = new google.maps.LatLng( (Math.random()*(85*2)-85), (Math.random()*(180*2)-180) );

try with something like this, or more generally:

function randomBetween(min, max) {
if (min < 0) {
    return min + Math.random() * (Math.abs(min)+max);
}else {
    return min + Math.random() * max;
}}

Post Status

Asked in February 2016
Viewed 1,381 times
Voted 11
Answered 1 times

Search




Leave an answer