使用jQuery自动完成插件进行Google Maps Api v3位置搜索

时间:2014-11-21 12:19:31

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

我想在我的地图中实现这个Location Search插件。它根本不工作,但控制台日志没有任何错误。你可以帮我解决这个问题吗,不幸的是我不是Javascript专家。

谢谢!

我的代码:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<input type="text" value="" id="searchbox" style=" width:800px;height:30px; font-size:15px;">
<div id="map-canvas" style="width:100%; height:650px; margin:0 auto;"></div>
<script>
var map = null;
            function initialize() 

            {
              var mapOptions = 
              {
                zoom: 8,
                center:new google.maps.LatLng(47.165843,18.9483089)
              };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
loadXMLFile();
  var geocoder = new google.maps.Geocoder();  
 jQuery(function() {
         jQuery("#searchbox").autocomplete({

           source: function(request, response) {

          if (geocoder == null){
           geocoder = new google.maps.Geocoder();
          }
             geocoder.geocode( {'address': request.term }, function(results, status) {
               if (status == google.maps.GeocoderStatus.OK) {

                  var searchLoc = results[0].geometry.location;
               var lat = results[0].geometry.location.lat();
                  var lng = results[0].geometry.location.lng();
                  var latlng = new google.maps.LatLng(lat, lng);
                  var bounds = results[0].geometry.bounds;

                  geocoder.geocode({'latLng': latlng}, function(results1, status1) {
                      if (status1 == google.maps.GeocoderStatus.OK) {
                        if (results1[1]) {
                         response(jQuery.map(results1, function(loc) {
                        return {
                            label  : loc.formatted_address,
                            value  : loc.formatted_address,
                            bounds   : loc.geometry.bounds
                          }
                        }));
                        }
                      }
                    });
            }
              });
           },
           select: function(event,ui){
      var pos = ui.item.position;
      var lct = ui.item.locType;
      var bounds = ui.item.bounds;

      if (bounds){
       map.fitBounds(bounds);
      }
           }
         });
     }); 
            }
            function loadXMLFile(){
            var filename = '<?php echo get_template_directory_uri(); ?>/scripts/mylist.xml.cache';
            jQuery.ajax({
                type: "GET",
                url: filename ,
                dataType: "xml",
                success: parseXML,
                error : onXMLLoadFailed
            });

            function onXMLLoadFailed(){
            alert("Error loading xml.");
                  jQuery.ajax({ url: '<?php echo get_template_directory_uri(); ?>/scripts/getxml.php',
          dataType: "xml",
         type: "GET"
});

            }
            function parseXML(xml){
        var bounds = new google.maps.LatLngBounds();
            jQuery(xml).find("Shop").each(function(){
                var nme = jQuery(this).find('Name').text();
                var address = jQuery(this).find('Address').text();
                var monday = jQuery(this).find('Monday').text();
                var tuesday = jQuery(this).find('Tuesday').text();
                var wednesday = jQuery(this).find('Wednesday').text();
                var thursday = jQuery(this).find('Thursday').text();
                var friday = jQuery(this).find('Friday').text();
                var saturday = jQuery(this).find('Saturday').text();
                var sunday = jQuery(this).find('Sunday').text();
                var lat = jQuery(this).find('Lat').text();
                var lng = jQuery(this).find('Lng').text();
                var markerCoords = new google.maps.LatLng(lat.replace(',', '.'),lng.replace(',', '.'));
                var image = {
              url: '<?php echo get_template_directory_uri(); ?>/images/markerimage2.png',
              size: new google.maps.Size(36, 24),
              origin: new google.maps.Point(0, 0),
              scaledSize: new google.maps.Size(36, 24)
            };


            var contentString = '<div id="infobox">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h5 id="firstHeading" class="firstHeading">'+nme+'</h5>'+
      '<div id="bodyContent">'+
      '<p><b>Openings:</b><br />'+
        'Monday: '+monday+'<br />'+
        'Tuesday: '+tuesday+'<br />'+
        'Wednesday: '+wednesday+'<br />'+
        'Thursday: '+thursday+'<br />'+
        'Friday: '+friday+'<br />'+
        'Saturday: '+saturday+'<br />'+
        'Sunday: '+sunday+'<br />'+

     '</p>'+
      '</div>'+
      '</div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

            var marker = new google.maps.Marker({
                    position: markerCoords,
                    map: map,
                    icon: image, 
                    title:nme
                });
                    google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });

            });

      jQuery.ajax({ url: '<?php echo get_template_directory_uri(); ?>/scripts/getxml.php',
          dataType: "xml",
         type: "GET"
});
        }
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

1 个答案:

答案 0 :(得分:0)

您正在查看的示例是使用旧版Google Maps API完成的。当前版本有一个自动完成小部件,可以处理您的用例。只需做

var input = document.getElementById('searchbox');
var autocomplete = new google.maps.places.Autocomplete(input);

每当一个人选择一个建议的位置时,将触发place_changed事件,因此您可以设置一个侦听器来检测此类事件并处理该地点:

google.maps.event.addListener(autocomplete, 'place_changed', function () {
    var place = autocomplete.getPlace();
    console.log('place changed', place);
});

根据您获得的地点类型,您应该选择何时最好将地图置于给定点上,或者将地图边界拟合到某个边界框上。