1

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)?

Sasha
  • 8,521
  • 23
  • 91
  • 174
  • Look here http://stackoverflow.com/questions/6388590/highlighting-borders-of-state-and-cities-of-us-in-google-map-api-3 . Somebody made a variable that lists the borders of the U.S. states. I'll see what I can do with this. Do you want the main land, or also Hawai and Alaska? – Emmanuel Delay Jul 17 '15 at 14:11

1 Answers1

4

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.

AniV
  • 3,997
  • 1
  • 12
  • 17
  • your code does only work for rectangular areas, You create a bounding box around the state or around usa, where parts of that rectangle are either in the water outside or in the neoigboruing state. – AlexWien Oct 19 '16 at 14:45