Sasha
Sasha

Reputation: 8705

Google Maps API - generate random cooridinates in USA

Is it possible to generate random latitude and longitude for Google maps API and to center on those coordinates (I need coordinates somewhere on continental part of USA)?

Upvotes: 1

Views: 4580

Answers (1)

AniV
AniV

Reputation: 4037

First of all you need to define the bounds of continental USA. You can get those with this webpage http://econym.org.uk/gmap/states.xml. One you have them you can use any data structure to populate and then can store them in a variable in a get variable. And then use the following code to generate random coordinates

  var bounds = yourarray.getBounds();
  map.fitBounds(bounds);
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  for (var i = 0; i < 100; i++) {
    var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
    var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
    var point = new google.maps.LatLng(ptLat, ptLng);
    if (google.maps.geometry.spherical.computeDistanceBetween(point, circle.getCenter()) < circle.getRadius()) {
      createMarker(map, point, "marker " + i);

Here is the function to create marker

function createMarker(map, point, content) {
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });
  google.maps.event.addListener(marker, "click", function(evt) {
    infowindow.setContent(content + "<br>" + marker.getPosition().toUrlValue(6));
    infowindow.open(map, marker);
  });
  return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);

Finally call the fitBounds(marker) to center and zoom the marker on the currently generated marker.

Upvotes: 4

Related Questions