单击地图上的位置以查找最近的位置

时间:2018-02-07 00:15:47

标签: javascript css google-maps-api-3

此代码获取数据库中的地址列表,并查找最接近输入地址的位置。我想知道是否可以只点击地图上的某个位置,让它找到最近的位置,而不是输入地址。有谁知道怎么做?

http://jsfiddle.net/vibajajo64/Lroa81am/3/

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <meta name="viewport" content="width=device-width, initial-scale=1">  

  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.js"></script> 

    <link rel="stylesheet" type="text/css" href="/css/result-light.css">  

      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script> 

  <style type="text/css">
     html,
 body,
 #map {
   margin: 0;
   padding: 0;
   height: 600px;
   width: 400px;
 }

 .text {
   width: 300px;
   height: 600px;
   background-color: white;
   overflow: scroll;
   overflow-y: auto;
   overflow-x: hidden;
 }

 #side_bar {
   z-index: 100;
   position: absolute;
   top: 135px;
   left: 400px;
 }

 #panel {
   z-index: -100;
   display: block;
   position: absolute;
   top: 135px;
   left: 400px;
 }

 #mdiv {
   z-index: 500;
   width: 25px;
   height: 25px;
   display: none;
   background-color: red;
   border: 1px solid black;
   position: absolute;
   left: 660px;
   top: 112px;
 }

 .mdiv {
   height: 25px;
   width: 2px;
   margin-left: 12px;
   background-color: black;
   transform: rotate(45deg);
   -ms-transform: rotate(45deg);
   /* IE 9 */
   -webkit-transform: rotate(45deg);
   /* Safari and Chrome */
   z-index: 1;
 }

 .md {
   height: 25px;
   width: 2px;
   background-color: black;
   transform: rotate(90deg);
   -ms-transform: rotate(90deg);
   /* IE 9 */
   -webkit-transform: rotate(90deg);
   /* Safari and Chrome */
   z-index: 2;
 }

 tr:nth-child(even) {
   background: #CCC
 }

 tr:nth-child(odd) {
   background: #FFF
 }
 .numberCircle {            
  /* float: left; */            
  border-radius: 50%;           
  behavior: url(PIE.htc);       
  /* remove if you don't care about IE8 */
  width: 18px;              
  height: 18px;             
  padding: 4px;             
  margin: 0px;              
  background: #fff;         
  border: 2px solid #666;       
  color: #666;              
  text-align: center;           
  font: 16px Arial, sans-serif;     
}                   

  </style>

  <title> by vibajajo64</title>







<script type='text/javascript'>//<![CDATA[

var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],


];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  // alert("init");
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
  for (i = 0; i < locations.length; i++) {
    var coordStr = locations[i][2];
    var coords = coordStr.split(",");
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    bounds.extend(pt);
    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + locations[i][1] + "&quot;);'>Get Directions</a>"
    });
    gmarkers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.html);
          infowindow.open(map, marker);
        }
      })
      (marker, i));
  }
  map.fitBounds(bounds);

  $("#mdiv").click(function() {
    $("#side_bar").css({
      "z-index": 100,
      "top": "135px"
    });
    $("#panel").css("z-index", -100);
    $("#mdiv").css("display", "none");
  })

}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (customerMarker) customerMarker.setMap(null);
      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      closest = findClosestN(results[0].geometry.location, 12);
      // get driving distance
      closest = closest.splice(0, 12);
      calculateDistances(results[0].geometry.location, closest, 12);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function findClosestN(pt, numberOfResults) {
  var closest = [];
  document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
    document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
    gmarkers[i].setMap(null);
    closest.push(gmarkers[i]);
    closest.sort(sortByDist);
  }

  return closest;
}

function sortByDist(a, b) {
  return (a.distance - b.distance)

}

function calculateDistances(pt, closest, numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  };
  for (var i = 0; i < closest.length; i++) {
    request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      var sidebarHtml = '<table>';

      var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      results.sort(sortByDistDM);
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        closest[i].setMap(map);
var letterMarkers = String.fromCharCode(97 + i);
closest[results[i].idx_closestMark].setLabel(letterMarkers);
       sidebarHtml += "<tr><td><div class='numberCircle'>" + letterMarkers + "</div><a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a></td></tr>"

      }
      sidebarHtml += '</table>';
      outputDiv.innerHTML = sidebarHtml;
    }
  });
}

function getDirections(origin, destination) {
  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      $("#side_bar").css({
        "z-index": -100,
        "top": "135px"
      });
      $("#panel").css("z-index", 100);
      $("#mdiv").css("display", "block");

      directionsDisplay.setPanel(document.getElementById('panel'));


    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);

//]]> 

</script>


</head>

<body>
  <div class="bh-sl-container">
  <div id="page-header">
    <h1 class="bh-sl-title">The Auditor Locator</h1>

  </div>

  <div class="bh-sl-form-container">
    <form id="bh-sl-user-location" method="post" action="#">
      <div class="form-input">
        <label for="bh-sl-address">Enter Address or Zip Code:</label>
        <input id="address" type="text" value="Paramus, NJ" />
        <input type="button" value="Submit" onclick="codeAddress();" />
      </div>
    </form>
  </div>

  <table border="0" style="height:100%">
    <tr style="height:100%">
      <td style="height:100%">
        <div id="map"></div>
      </td>
      <td>
        <div id="side_bar" class='text'></div>
        <div id="panel" class='text'></div>
      </td>
    </tr>
  </table>


  <div id="info"></div>
  <div id="mdiv">
    <div class="mdiv">
      <div class="md">
      </div>
    </div>
  </div>


  <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent){
    window.parent.parent.postMessage(["resultsFrame", {
      height: document.body.getBoundingClientRect().height,
      slug: "Lroa81am"
    }], "*")
  }
</script>

</body>

</html>

1 个答案:

答案 0 :(得分:1)

您可以添加一个事件监听器来绑定点击,然后您可以运行一个函数来执行您需要的任何操作。

google.maps.event.addListener(map, "click", function (event) {
    codeAddressByClick(event.latLng)
}); //end addListener

要获得最近的位置,您可以设置一个函数来获取点击/事件Lat和Lng,然后调用findClosestN(),如下所示:

function codeAddressByClick(locationLL) {
        closest = findClosestN(locationLL, 12);
        // get driving distance
        closest = closest.splice(0, 12);
        calculateDistances(locationLL, closest, 12);
}

单击时你也可以装入界限:

    google.maps.event.addListener(map, "click", function (event) {
       codeAddressByClick(event.latLng);
       //fitbounds of the click position
       var newBounds = new google.maps.LatLngBounds(event.latLng,event.latLng);
       map.fitBounds( newBounds );
       map.setZoom(9);
    }); //end addListener

请参阅:http://jsfiddle.net/h0Lr0jen/

编辑:

  

使用Google反向地理编码使用基于点击位置的地址填充搜索字段。

需要对传递给codeAddressByClick()的参数进行细微更改,并且需要进行Ajax对Google Maps Geocoding API的调用,以便通过地理编码获取实际地址。

google.maps.event.addListener(map, "click", function (event) {
    codeAddressByClick(event)
}); //end addListener

然后:

function codeAddressByClick(locationV) {
        closest = findClosestN(locationV.latLng, 12);
        closest = closest.splice(0, 12);
        calculateDistances(locationV.latLng, closest, 12);
        //MAKE AJAX CALL TO GOOGLE API BY CLICKED LAT & LNG CLICK POSITION
        jQuery.get( "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + locationV.latLng.lat() + ',' + locationV.latLng.lng(), function( data )
        {
         if(data.results[0].formatted_address){
          //POPULATE THE ADDRESS FIELD
          jQuery('#address').val(data.results[0].formatted_address);
         }
        });
} 

请参阅小提琴:http://jsfiddle.net/h0Lr0jen/1/