谷歌地图 - 寻找所有的标记给定半径的Javascript / PHP的内部 [英] Google Maps - Finding all the markers inside a given radius Javascript/Php

查看:243
本文介绍了谷歌地图 - 寻找所有的标记给定半径的Javascript / PHP的内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本,会显示自定义标记在谷歌地图,但我想包括输入文本框,可以输入一个城市/州和zip- code,看看是否有任何标记内可以说从那个城市/州或zip- $ C $使用C 400英里。我喜欢它,如果地图上可以是动态的,以便在您键入出城市/州或zip- code将通过摆脱所有其他标记,并只留一个是在在地图上显示结果即半径,如果是太难,那么一个简单的ALTER中说什么单位是最接近的也都会好的:)我搜索,发现有些人说,我应该加载几何库,并使用 computeDistanceBetween()来找到每个标志物的距离从中心点,但我不知道该怎么办了zip- code部分或如何将所有这些一起工作。

下面是我的code:

 <!DOCTYPE HTML>
< HTML>
< HEAD>
<元字符集=utf-8/>
<冠军>< /标题>
<脚本类型=文/ JavaScript的SRC =htt​​p://maps.google.com/maps/api/js?sensor=false>< / SCRIPT>
&LT;脚本类型=文/ JavaScript的 src="http://google-maps-utility-library-v3.google$c$c.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>

&LT;脚本类型=文/ JavaScript的&GT;
   VAR形象=新google.maps.MarkerImage(标记的图像/ image.png,新google.maps.Size(40,35),新google.maps.Point(0,0),新google.maps.Point (20,35));

   VAR阴影=新google.maps.MarkerImage(
                            标记的图像/ shadow.png',
                            新google.maps.Size(62,35),
                            新google.maps.Point(0,0),
                            新google.maps.Point(20,35)
                          );

   VAR形状= {
                坐标: [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],
                类型:'聚'
          };

     //这个变量将收集最终将放在side_bar的HTML
     VAR side_bar_html =;

     //数组来保存所用的side_bar标记和HTML的副本
     //因为函数闭包伎俩行不通的有
     变种gmarkers = [];

     //全局图变
     VAR地图= NULL;
     VAR圈= NULL;

     //标记聚类器
     变种MC;
     变种mcOptions = {gridSize:10,maxZoom:8};

     //全球信息窗口
     VAR信息窗口=新google.maps.InfoWindow();

     //地理codeR
     VAR地理codeR =新google.maps.Geo codeR();
     VAR地址=新阵列(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内容=新阵列(号机组#0206,
                        号机组## 2003,
                        单位无#0176,
                        单位无## 2001年
                        单位无#0124,
                        单位无#0157,
                        号机组## 0162,
                        单位无#0104,
                        单位无#0118,
                        号机组## 2007,
                        单位无#0112,
                        单位无#0139,
                        单位无#0205,
                        单位无#0127,
                        单位无#0187,
                        单位无#0105,
                        单位无#0214,
                        单位无#0186,
                        单位无#0173,
                        单位无#0134,
                        单位无#0128,
                        单位无#0125,
                        单位无#0158,
                        单位无#0193,
                        单位无#0201);

     //最小值和最大值的倍频限制,随机数
     //保留范围pretty的小,所以标记保持附近
     VAR分钟= 0.999999;
            VAR最大= 1.000001;

    功能createMarker(经纬度,文字){
      VAR的标记=新google.maps.Marker({
         可拖动:假的,
         raiseOnDrag:假的,
         图标:图像,
         阴影:阴影,
         外形:外形,
         位置:经纬度,
         地图:地图
       });

     ///得到标记数组目前在集群
     变种allMarkers = mc.getMarkers();

     //检查,看看是否有任何现有的标记匹配新标记的经纬度
      如果(allMarkers.length!= 0){
        对于(i = 0; I&LT; allMarkers.length;我++){
          VAR existingMarker = allMarkers [I]
          VAR POS = existingMarker.getPosition();

          如果(latlng.equals(POS)){
            文=文+&放大器;+含量[I];
          }
        }
      }

      google.maps.event.addListener(标记,'点击',函数(){
        infowindow.close();
        infowindow.setContent(文本);
        infowindow.open(地图,标记);
      });
      mc.addMarker(标记);
      返回标记;
    }
    函数初始化(){
        VAR的选择= {
            变焦:4,
            中心:新google.maps.LatLng(39.8282,-98.5795),
            mapTypeId:google.maps.MapTypeId.ROADMAP
        };
        地图=新google.maps.Map(的document.getElementById(地图),选项);

    //标记集群
        变种gmarkers = [];
        MC =新MarkerClusterer(地图,[],mcOptions);
        对于(i = 0; I&LT; address.length;我++){
           VAR PTSTR =地址[I]
           变种的coords = ptStr.split(,);
           变种经纬度=新google.maps.LatLng(parseFloat(的coords [0]),parseFloat(的coords [1]));
           gmarkers.push(createMarker(经纬度,内容[我]));
        }
    }

          函数codeAddress(){
            VAR地址=的document.getElementById(地址)的价值。
            VAR半径= parseInt函数(的document.getElementById('半径')值,10)* 1609.34;
            地理coder.geo code({地址:地址},功能(结果状态){
              如果(状态== google.maps.Geo coderStatus.OK){
                map.setCenter(结果[0] .geometry.location);
                VAR的标记=新google.maps.Marker({
            //地图:地图,&LT;  - 取消注释显示红色标记
                    位置:结果[0] .geometry.location
                });
                如果(圈子)circle.setMap(空);
                圈=新google.maps.Circle({中心:marker.getPosition()
                                                 半径:半径,
                                                 fillOpacity:0.35,
                                                 填充颜​​色:#FF0000
                                                 图:图});
                VAR边界=新google.maps.LatLngBounds();
            变种foundMarkers = 0;
                对于(VAR I = 0; I&LT; gmarkers.length;我++){
                  如果(google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) &LT;半径) {
                    bounds.extend(gmarkers [I] .getPosition())
                    gmarkers [I] .setMap(图)
            foundMarkers ++;
                  } 其他 {
                    gmarkers [I] .setMap(空);
                  }
                }
                如果(foundMarkers大于0){
                  map.fitBounds(边界);
            } 其他 {
                  map.fitBounds(circle.getBounds());
                }
              } 其他 {
                警报(状态);
              }
            });
          }

    VAR信息窗口=新google.maps.InfoWindow(
      {
        大小:新google.maps.Size(150,50)
      });


    功能handleKey preSS(五){
     VAR键= e.key code || e.which;
      如果(关键== 13){
         codeAddress();
      }
    }

    功能handleResetKey preSS(五){
        如果map.setZoom(4)(map.getZoom()= 4!);
          map.setCenter(新google.maps.LatLng(39.8282,-98.5795));
        。的document.getElementById(地址)值='请输入城市或省份code';
        。的document.getElementById(半径)值='200';
    }
    &LT; / SCRIPT&GT;

    &LT;风格&GT;
    HTML,身体,#map {
    高度:100%;
    宽度:100%;
    保证金:0;
    填充:0;
    }
    。汽车,STYLE1 {
        文本对齐:中心;
    }
      #footer {
        位置:绝对的;
        底部:0;
        高度:40PX;
        的margin-top:40PX;
     / *边界:1px的固体蓝色; * /
      }
    &LT; /风格&GT;
    &LT; /头&GT;
    &LT;身体的onload ='初始化()'&GT;
    &LT; D​​IV ID =地图&GT;&LT; / DIV&GT;
    &LT; D​​IV ID =页脚级=自动样式1的风格=左:0px;底部:0;宽度:100%&GT;
          &LT;输入类型=文本ID =地址值=输入城市或省份code的onclick =如果(THIS.VALUE =='请输入城市或省份code') {THIS.VALUE =''}的onblur =如果(THIS.VALUE ==''){THIS.VALUE ='请输入城市或省份code'}onkey preSS =handleKey preSS(事件);风格=宽度:183px&GT;
          &LT;输入类型=按钮值=搜索的onclick =codeAddress();&GT;
          &LT;输入类型=按钮值=复位的onclick =handleResetKey preSS();&GT;
          &LT;输入类型=文本ID =半径值=200的风格=宽度:42PX的onclick =如果(THIS.VALUE =='200'){THIS.VALUE =''}的onblur = 如果(THIS.VALUE ==''){THIS.VALUE ='200'}onkey preSS =handleKey preSS(事件);&GT;英里
    &LT; / DIV&GT;
    &LT; /身体GT;
&LT; / HTML&GT;
 

解决方案

下面是如何,你可以用地理编码API和一些简单的几何形状解决这样的一个例子。

(请注意,我已经很难$ C $光盘简洁的地址和半径。)

  //我们假设你有标记的数组
变种标记物= [];

//为了查找一个zip- $ C $的位置C可以使用地理编码API:
// https://developers.google.com/maps/documentation/geocoding/
VAR地理code_api_base_url =?http://maps.googleapis.com/maps/api/geo$c$c/json;
VAR PARAMS = {
    地址:05673,
    成分:国家:美国
    传感器:假的
}
//这是结果集区标记
变种in_area = [];

// http://maps.googleapis.com/maps/api/geo$c$c/json?address=05673&components=country:US&sensor=false
$ .getJSON(GEO code_api_base_url + $ .PARAM(PARAMS),功能(数据){

    VAR的位置,search_area,in_area = [];

    位置=数据['结果'] [0] ['address_components'] ['几何'] ['位置'];

    //我们创建了一个圆圈,看看内:
    sea​​rch_area = {
        则strokeColor:#FF0000,
        strokeOpacity:0.8,
        strokeWeight:2,
        中心:新google.maps.LatLng(location.lat,location.lon)
        半径:500
    }

    sea​​rch_area =新google.maps.Circle(search_area);

    $每个(标记功能(我,标记){
       如果(google.maps.geometry.poly.containsLocation(marker.getPosition(),search_area)){
         in_area.push(标记);
       }
    });

    console.info(in_area);

});
 

I have this script that will show custom markers on a google map, but I would like to include a input text-box and be able to enter a city/state and a zip-code and see if there are any markers within lets say 400 miles from that city/state or zip-code. I would love it if the map can be dynamic so as you type out the city/state or zip-code it will show the results on the map by getting rid of all the other markers and leaving only the one that is within that radius, if that is too hard then a simple alter box saying what unit is the closest will also be OK :) I searched and found some say that I should load the geometry library and use computeDistanceBetween() to find the distance of each marker from your center point but I have no idea how to do the zip-code part or how to put all of this together to work.

Here is my code:

<!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>

解决方案

Here is an example of how you could solve this with the geocoding API and some simple geometry.

(Note that I have hardcoded the address and radius for brevity.)

// 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);

});

这篇关于谷歌地图 - 寻找所有的标记给定半径的Javascript / PHP的内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆