views:

187

answers:

3

On my web page I have already a Google Maps API with a search bar (see code below) and at first the user pinpoints an address. Then the User is be able to search businesses around this point with a search bar. Before search is complete I'd like to draw a circle around this address for instance with a distance of 15 km. The search should show only results within this circle. It would be nice if you also could move the circle... How can I do this with Google Maps?

<script type="text/javascript">
   var map = null;
     var geocoder = null;     

    function initialize() {
          /* Initialize the Google Maps */
           if (GBrowserIsCompatible()) {

         map = new GMap2(document.getElementById("map"));
         map.setCenter(new GLatLng(50.786916, 6.101360), 16);
         var customUI = map.getDefaultUI();
     customUI.controls.scalecontrol = false;
     map.setUI(customUI);
         var options = {
          onSearchCompleteCallback:function(searcher){
           var resultcontent = '';
           if (searcher.results && searcher.results.length > 0) {
            $("#ResultGrid").clearGridData(true);
            for (var i = 0; i < searcher.results.length; i++) {
             var result = searcher.results[i];

             // Split address-lines to get Zipcode
             TempString = result.addressLines[1];
             var ZipCode = TempString.split(/\b[^0-9]/);

             // construct the data array
             var InputData = {Firma:result.titleNoFormatting, Adresse:result.addressLines[0], Postleitzahl:ZipCode[0], Ort:result.city, Telefonnummer:result.phoneNumbers[0].number}; 

             // Apply data to grid
             jQuery("#ResultGrid").addRowData(i, InputData);
             $("#Result").show("slow");
            }
           } else {
            $("#Dialog").html("<p><span class=\"ui-icon ui-icon-info\" style=\"float:left; margin:0 7px 20px 0;\"></span>Kein Suchergebnis!</p>");
        $("#Dialog").dialog("option", "title", "Hinweis:");
        $("#Dialog").dialog("open");
            $("#Dialog").html("Keine Ergebnisse gefunden!");
        $("#Dialog").dialog("option", "title", "Hinweis:");
        $("#Dialog").dialog("open");
           }
          }
         };
         localSearch = new google.maps.LocalSearch(options);
         map.addControl(localSearch);
         map.removeControl(GScaleControl);

         geocoder = new GClientGeocoder();
         $("#map").hide("fast");
         $("#Result").hide("fast");
       }
     } 
     function showAddress(address, CompleteAdd) {
       if (geocoder) {
         geocoder.getLatLng(
           address,
           function(point) {
             if (!point) {
              $("#Dialog").html("<p><span class=\"ui-icon ui-icon-info\" style=\"float:left; margin:0 7px 20px 0;\"></span>"+address+" nicht gefunden</p>");
        $("#Dialog").dialog("option", "title", "Hinweis:");
        $("#Dialog").dialog("open");
             } else {
               map.setCenter(point, 16);
               var marker = new GMarker(point);
               map.addOverlay(marker);
               marker.openInfoWindowHtml(CompleteAdd);
             }
           }
         );
       }
       $("#map").show("fast");
     }
  </script>

<body onload="initialize()" onunload="GUnload()">
  <div class="main" align="center">
   <div id="Dialog">
    <p><span class="ui-icon ui-icon-info" style="float:left; "></span>Dialog text</p>
   </div>
   <br/>
   <div id="map" style="width: 850px; height:450px; padding:10px; font-size: medium; color:#853805; background-color:#FFE8CF;"></div>
  </div>
 </body>
+1  A: 

Draw circle using polylines. You can do it by looping from 0 to 2*PI (0..6.28) where number of steps defines a "smothness" of your circle. To draw a circle points of your polyline will be ( RADIUS*sin(loop_counter) , RADIUS*cos(loop_counter) ).

You can search in range just by calculating distance from your starting point, distance = sqrt( (x1-x2)^2 + (y1-y2)^2 ) where x1,y1 is your possision and x2,y2 is position of object that you checking is in range or not. If value of this expression is smaller than X, that means that object is in range (x) you looking for. But unit of this range is something like degree-on-earth. To recalculate this to kilometers you need multiply it by about 67 (check for example on google Earth how much degrees in your region approximately equals one kilometer or mile)

Of course, earth isn't exactly sphere, but precise function is very complicated, and above solution should work.

Edit: To do a search, you must have some data to search in. Let's say it's database where saved objects have longitude and altitude values. Now, to find objects that are in range from startpoint X,Y, you have to compare every object location with your X and Y by computing a distance to your point and check that distance is smaller or equal a range within you looking for objects. Example query looks like:

   SELECT * FROM objects_database WHERE SQRT((googlex-$lat)*(googlex-$lat)+(googley-$lng)*(googley-$lng)) < $realthemax

Where $lat and $lng is your staring point and googlex and googley are columns in database with lat and lng values of object.

$realthemax is your range. I call it that way because we computing on degree unit, so you have to convert your range (for example in kilometers) to "degrees-on-earth". I did this that way:

  • my expression and geographic location of Warsaw and Moscov returns range about 16.97
  • i check this range in real world in Goole Earth, and on straight line that is 1149km
  • so 1 "degree-on-earth" is 67.67 kilometers

So if range that you want to search in kilometers equal $themax, i get range value for database like this:

$realthemax = $themax/67.67;

Must remember that those values depends on your location, and earth is not perfect sphere so, this expression will not be particular espacially on top or bottom of the earth. This way of searching will be like looking for objects in perfect circle ON MAP (but shouldn't), you can see a drfference from perfect circle here:

http://gmaps-samples-v3.googlecode.com/svn/trunk/circle-overlay/circle-overlay.html

killer_PL
Ok, drawing the circle by looping from 0 to PI works fine, but I don't understand completely your solution with search in range...Maybe can you give an example?
Laurenz
+1  A: 

V3 of GoogleMaps has a circle overlay option just give it a radius, some styling and bind it to a marker. If the marker is dragable the circle will follow it. Take a look at the demo here: http://gmaps-samples-v3.googlecode.com/svn/trunk/circle-overlay/circle-overlay.html

I had it hooked up to a jQueryUI slider with an onChange event to set the radius of the circle and bound to a moveable marker to set the position.

jkilbride
A: 

See here: http://maps.forum.nu/gm_drag_polygon.html

Ready to plug'n'play into V2. :-)

Marcelo