当前位置: 首页 > 面试题库 >

Google Maps-查找给定半径内的所有标记Javascript / Php

慎兴业
2023-03-14
问题内容

我有这个脚本,它将在Google地图上显示自定义标记,但是我想包含一个输入文本框,并且能够输入城市/州和邮政编码,并查看其中是否有任何标记(例如400)距该城市/州或邮政编码的英里。如果地图可以是动态的,我会喜欢的,因此当您输入城市/州或邮政编码时,它会摆脱所有其他标记并仅保留该半径范围内的一个标记,从而在地图上显示结果,如果那太难了,那么说一个最接近单位的简单更改框也可以:)我搜索并发现有人说我应该加载几何库并用于computeDistanceBetween()查找每个标记到您的中心点的距离,但是我不知道如何执行邮政编码部分或如何将所有这些组合在一起工作。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript"  src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>

<script type="text/javascript"> 
   var image = new google.maps.MarkerImage("marker-images/image.png",new google.maps.Size(40,35),new google.maps.Point(0,0),new google.maps.Point(20,35));

   var shadow = new google.maps.MarkerImage(
                            'marker-images/shadow.png',
                            new google.maps.Size(62,35),
                            new google.maps.Point(0,0),
                            new google.maps.Point(20,35)
                          );

   var shape = {
                coord: [27,0,30,1,32,2,34,3,35,4,36,5,38,6,39,7,39,8,39,9,39,10,38,11,37,12,33,13,34,14,34,15,33,16,32,17,31,18,27,19,28,20,28,21,27,22,26,23,22,25,23,26,24,27,24,28,24,29,24,30,24,31,24,32,23,33,22,34,17,34,16,33,15,32,15,31,14,30,14,29,15,28,15,27,16,26,17,25,13,23,12,22,11,21,11,20,12,19,8,18,7,17,6,16,5,15,5,14,6,13,2,12,1,11,0,10,0,9,0,8,0,7,1,6,3,5,4,4,5,3,7,2,9,1,12,0,27,0],
                type: 'poly'
          };

     // this variable will collect the html which will eventually be placed in the side_bar 
     var side_bar_html = "";

     // arrays to hold copies of the markers and html used by the side_bar 
     // because the function closure trick doesnt work there 
     var gmarkers = [];

     // global "map" variable
     var map = null;
     var circle = null;

     //marker clusterer
     var mc;
     var mcOptions = {gridSize: 10, maxZoom: 8};

     //global infowindow
     var infowindow = new google.maps.InfoWindow();

     //geocoder
     var geocoder = new google.maps.Geocoder(); 
     var address = new Array("41.8119,-87.6873",
                        "40.7888,-74.056",
                        "41.8119,-87.6873",
                        "48.6681,-97.3627",
                        "44.9793,-93.273",
                        "39.4857,-75.6775",
                        "41.8119,-87.6873",
                        "42.0203,-87.9059",
                        "32.7812,-96.7903",
                        "27.5159,-99.4941",
                        "32.7812,-96.7903",
                        "37.5608,-95.6684",
                        "41.8119,-87.6873",
                        "38.3763,-97.6702",
                        "42.2458,-83.2491",
                        "41.8122,-91.9139",
                        "41.8397,-88.0887",
                        "41.8397,-88.0887",
                        "38.5128,-122.787",
                        "41.8397,-88.0887",
                        "42.8863,-87.892",
                        "42.8863,-87.892",
                        "30.7539,-83.3321",
                        "39.889,-84.2422",
                        "34.106,-83.589");
     var content = new Array("Unit No# 0206",
                        "Unit No# #2003",
                        "Unit No# 0176",
                        "Unit No# #2001",
                        "Unit No# 0124",
                        "Unit No# 0157",
                        "Unit No# #0162",
                        "Unit No# 0104",
                        "Unit No# 0118",
                        "Unit No# #2007",
                        "Unit No# 0112",
                        "Unit No# 0139",
                        "Unit No# 0205",
                        "Unit No# 0127",
                        "Unit No# 0187",
                        "Unit No# 0105",
                        "Unit No# 0214",
                        "Unit No# 0186",
                        "Unit No# 0173",
                        "Unit No# 0134",
                        "Unit No# 0128",
                        "Unit No# 0125",
                        "Unit No# 0158",
                        "Unit No# 0193",
                        "Unit No# 0201");

     //min and max limits for multiplier, for random numbers
     //keep the range pretty small, so markers are kept close by
     var min = .999999;
            var max = 1.000001;

    function createMarker(latlng,text) {
      var marker = new google.maps.Marker({
         draggable: false,
         raiseOnDrag: false,
         icon: image,
         shadow: shadow,
         shape: shape,
         position: latlng,
         map: map
       });

     ///get array of markers currently in cluster
     var allMarkers = mc.getMarkers();

     //check to see if any of the existing markers match the latlng of the new marker
      if (allMarkers.length != 0) {
        for (i=0; i < allMarkers.length; i++) {
          var existingMarker = allMarkers[i];
          var pos = existingMarker.getPosition();

          if (latlng.equals(pos)) {
            text = text + " & " + content[i];
          }                   
        }
      }

      google.maps.event.addListener(marker, 'click', function() {
        infowindow.close();
        infowindow.setContent(text);
        infowindow.open(map,marker);
      });
      mc.addMarker(marker);
      return marker;
    }
    function initialize(){
        var options = { 
            zoom: 4, 
            center: new google.maps.LatLng(39.8282,-98.5795), 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        };
        map = new google.maps.Map(document.getElementById('map'), options);

    //marker cluster
        var gmarkers = [];
        mc = new MarkerClusterer(map, [], mcOptions);
        for (i=0; i<address.length; i++) {
           var ptStr = address[i];
           var coords = ptStr.split(",");
           var latlng = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
           gmarkers.push(createMarker(latlng,content[i]));
        }
    }

          function codeAddress() {
            var address = document.getElementById('address').value;
            var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
            geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
            //        map: map,  <-- uncomment to show red marker
                    position: results[0].geometry.location
                });
                if (circle) circle.setMap(null);
                circle = new google.maps.Circle({center:marker.getPosition(),
                                                 radius: radius,
                                                 fillOpacity: 0.35,
                                                 fillColor: "#FF0000",
                                                 map: map});
                var bounds = new google.maps.LatLngBounds();
            var foundMarkers = 0;
                for (var i=0; i<gmarkers.length;i++) {
                  if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) {
                    bounds.extend(gmarkers[i].getPosition())
                    gmarkers[i].setMap(map);
            foundMarkers++;
                  } else {
                    gmarkers[i].setMap(null);
                  }
                }
                if (foundMarkers > 0) {
                  map.fitBounds(bounds);
            } else {
                  map.fitBounds(circle.getBounds());
                }
              } else {
                alert(status);
              }
            });
          }

    var infowindow = new google.maps.InfoWindow(
      { 
        size: new google.maps.Size(150,50)
      });


    function handleKeyPress(e){
     var key=e.keyCode || e.which;
      if (key==13){
         codeAddress();
      }
    }

    function handleResetKeyPress(e){
        if (map.getZoom() != 4) map.setZoom(4);
          map.setCenter(new google.maps.LatLng(39.8282, -98.5795));
        document.getElementById("address").value = 'Enter City,State or Zipcode';
        document.getElementById("radius").value = '200';
    }
    </script>

    <style>
    html, body, #map {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    }
    .auto-style1 {
        text-align: center;
    }
      #footer {
        position : absolute;
        bottom : 0;
        height : 40px;
        margin-top : 40px;
     /* border: 1px solid blue; */
      }
    </style>
    </head>
    <body onload='initialize()'>
    <div id="map"></div>
    <div id="footer" class="auto-style1" style="left: 0px; bottom: 0; width: 100%">
          <input type="text" id="address" value="Enter City,State or Zipcode" onclick="if(this.value=='Enter City,State or Zipcode'){this.value=''}" onblur="if(this.value==''){this.value='Enter City,State or Zipcode'}" onkeypress="handleKeyPress(event);" style="width: 183px">
          <input type="button" value="Search" onclick="codeAddress();">
          <input type="button" value="Reset" onclick="handleResetKeyPress();">
          <input type="text" id="radius" value="200" style="width: 42px" onclick="if(this.value=='200'){this.value=''}" onblur="if(this.value==''){this.value='200'}" onkeypress="handleKeyPress(event);"> miles
    </div>
    </body>
</html>

问题答案:

这是一个示例,说明如何使用地址解析API和一些简单的几何图形来解决此问题。

(请注意,为简洁起见,我已经硬编码了地址和半径。)

// we assume that you have an array of markers
var markers = [];

//In order to lookup the the position of a zip-code you can use the geocoding API:
// https://developers.google.com/maps/documentation/geocoding/
var geocode_api_base_url = "http://maps.googleapis.com/maps/api/geocode/json?";
var params = {
    adress : 05673,
    components : "country:us",
    sensor : false
}
// This is the result set of markers in area
var in_area = [];

//  http://maps.googleapis.com/maps/api/geocode/json?address=05673&components=country:US&sensor=false
$.getJSON( geocode_api_base_url + $.param(params), function(data) {

    var location, search_area, in_area = [];

    location = data['results'][0]['address_components']['geometry']['location'];

    // We create a circle to look within:
    search_area = {
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        center : new google.maps.LatLng(location.lat, location.lon),
        radius : 500
    }

    search_area = new google.maps.Circle(search_area);

    $.each(markers, function(i,marker) {
       if (google.maps.geometry.poly.containsLocation(marker.getPosition(), search_area)) {
         in_area.push(marker);
       }
    });

    console.info(in_area);

});


 类似资料:
  • 我正在研究一个问题,基本上可以归结为以下几点: 给定: null 对于这样一个位置,有什么算法的想法吗?我最终将使用java实现,但我可以使用PsuedoCode。

  • 问题内容: 这是CSV格式的PostgreSQL示例。 我在世界各地有成千上万行这样的跨越坐标。 我只想查询表中特定半径内的坐标。如何使用PostGIS和PostgreSQL做到这一点? 问题答案: 我结合了欧文(Erwin)和帕特里克(Patrick)的答案。

  • 我有N个数字,让我们说。现在我想找出在给定范围内有多少对数字。(L和R给定)。数字对=两个数字相同。我的方法:

  • 我在PostgreSQL/PostGIS中有一个名为的表,其中有两个几何列:()和(),指示旅程的开始和结束位置。 我还有一个单独的表,名为,带有几何列(),指示办公室的位置。 我的目标是从表中选择目标距离任何办公地点1000米以内的记录。 我需要激发什么查询才能获得所需的结果?

  • 我有一个有向图,有大约1000个顶点和3000条边,其中包含圈。 我试图从给定顶点找到所有下游(外)路径。 使用以下Gremlin查询时 对于某些路径,由于周期的原因,需要花费很长时间才能得到结果,尽管simplePath步骤应该可以防止这种情况发生。 我尝试优化查询,并使用“聚合”步骤和“不使用”步骤两次遍历同一顶点,但现在跳过了一些顶点。 谢谢

  • 我正在使用meanstack应用程序。所以我有mongodb系列,其中包含全球各地的位置。模式loook如下所示。 选择圆内所有点(预定义点和预定义半径)的有效方法是什么。。?? 使用SQL查询也可以做到这一点。但我想要一种有效的方法,不需要逐个迭代,检查它是否在该半径内。