Google Maps API,搜索自动完成而不是缩放 [英] Google Maps API, search autocomplete not zooming

查看:88
本文介绍了Google Maps API,搜索自动完成而不是缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在审核和使用使用Places API的Google Maps API商店定位器示例。我已经添加了markercluster api以允许对1800个标记进行聚类。



我现在的问题是如何修复添加之前添加的搜索自动完成功能MarkerCluster代码。在添加代码之前,搜索现有地点文本框会将地图放大并居中放置到我选择的位置。



我想我需要将搜索代码放入初始化脚本,但我不知道在哪里。


$ b $ p <下面的搜索代码>

  $('#search_ex_places' ).blur(function(){//一旦用户选择了一个已存在的地方


var marker = 0;
var place = $(this).val() ;
//初始化值
var exists = 0;
var lat = 0;
var lng = 0;
$('#saved_places option')。 (function(index){//循环保存位置
var cur_place = $(this).data('place'); //当前地点描述

//如果当前地点在循环中等于选定的地方
//然后将信息设置为它们所关注的字段
if(cur_place == place){
exists = 1;
$(' ($'(this).data('id'));
lat = $(this).data('lat');
lng = $(this).data ('lng');
$('#n_place')。val($(this).data('place'));
$('#n_description')。val($(this ).data('description'));

alert('lat:'+ lat + ',lng:'+ lng); //将这个提示放在这里,看看lat / lng值在哪里

// map.setCenter(new google.maps.LatLng(lat,lng) ); //将地图中心设置为位置的坐标
// map.setZoom(17); //设置自定义缩放级别17
//$('#map_canvas').gmap('get','map').setOptions({'center':(25.86568260193,-80.19351196289)});


var datcenter = new google.maps.LatLng(lat,lng);
var map = new google.maps.Map(document.getElementById('map'),{
zoom:17,
center:datcenter,
mapTypeId:google.maps。 MapTypeId.ROADMAP

});
var marker = new google.maps.Marker({
position:map.getCenter(),
map:map,
title:$(this).data('place ')
});


}
});

if(exists == 0){//如果地方不存在,则清空所有文本字段和隐藏字段
$('input [type = text],input [类型=隐藏] ')VAL('');

} else {
//设置所选地点的坐标
var position = new google.maps.LatLng(lat,lng);

//设置标记位置
marker.setMap(map);
marker.setPosition(position);

//设置地图的中心
map.setCenter(marker.getPosition());
map.setZoom(17);


}
});

[搜索结束代码]



高在搜索代码的上面,我有这个markercluster代码工作:

[代码开始]

 < script type =text / javascript> 

// var src ='https://developers.google.com/maps/tutorials/kml/westcampus.kml';

// var src ='http://urgentcarepro.com/map/us_states.kml';



函数initialize(){
var center = new google.maps.LatLng(37.4419,-122.1419);

var map = new google.maps.Map(document.getElementById('map'),{
zoom:3,
center:center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});



var input = document.getElementById('search_new_places'); //获取要用作自动完成输入的元素
var autocomplete = new google.maps.places.Autocomplete(input); //将其设置为自动完成的输入
autocomplete.bindTo('bounds',map); //将结果偏向地图视口


var markers = [];
for(var i = 0; i <1860; i ++){

createMarker(i);
}

函数createMarker(i){

var dataPhoto = data.photos [i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,
dataPhoto.longitude);
var marker = new google.maps.Marker({
position:latLng,
draggable:true,//使标记可以拖动
title:dataPhoto.photo_title,// title我猜
});




var contentString ='< div id =contentstyle =width:500px;>'+
'<& ; div id =siteNotice>'+
'< / div>'+
'< h1 id =firstHeadingclass =firstHeading>'+ dataPhoto.photo_title +'< ; / h1>'+
'< div id =bodyContent>'+
'< p>< b>'+ dataPhoto.photo_title +'< / b> ;, Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。请将您的评论发送给我们,我们会尽快为您解答。 Duis aute irure dolor in renhenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum< / p>'+
'< p>访问网站:< a href =#>'+
'点击此处< / a> '+
'< / p>'+
'< / div>'
'< / div>';

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


$ b google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});


//当从搜索字段中选择某个地点时执行
google.maps.event.addListener(autocomplete,'place_changed',function(){

//获取有关自动填充文本字段中所选位置的信息
var place = autocomplete.getPlace();

if(place.geometry.viewport){// for (大洲,国家)
map.fitBounds(place.geometry.viewport); //将地图中心设置为位置的坐标
} else {//对于那些位于
map.setCenter(place.geometry.location); //将地图中心设置为位置坐标
map.setZoom(17); //设置一个自定义缩放级别为17
}

marker.setMap(map); //设置地图供标记使用
marker.setPosition(place.geometry。位置); //将标记绘制到位置坐标

});


markers.push(marker);

}
var markerCluster = new MarkerClusterer(map,markers);




$ b函数loadKmlLayer(src,map){
var kmlLayer = new google.maps.KmlLayer(src,{
suppressInfoWindows:true,
preserveViewport:false,
map:map
});
google.maps.event.addListener(kmlLayer,'click',function(event){
var content = event.featureData.description;
var testimonial = document.getElementById('capture' );
testimonial.innerHTML = content;
});
}



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



< / script>

[code ends]

解决方案

最简单的解决方法是使地图可变全局。然后在您的搜索功能中使用全局变量。

pre $ var map = new google.maps.Map(document.getElementById('map '),{
zoom:17,
center:datcenter,
mapTypeId:google.maps.MapTypeId.ROADMAP

});

  map = new google.maps.Map(document.getElementById('map'),{
zoom:17,
center:datcenter,
mapTypeId:google.maps.MapTypeId .ROADMAP

});

或者删除这些行。

  function initialize(){
var center = new google.maps.LatLng(37.4419,-122.1419);

var map = new google.maps.Map(document.getElementById('map'),{
zoom:3,
center:center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//其余的初始化代码

收件人:

  //声明全局映射变量
var map = null;
函数initialize(){
var center = new google.maps.LatLng(37.4419,-122.1419);

//初始化全局地图变量
map = new google.maps.Map(document.getElementById('map'),{
zoom:3,
center :center,
mapTypeId:google.maps.MapTypeId.ROADMAP
});
//其余的初始化代码


I've been reviewing and working with the Google Maps API store locator example that uses the Places API. I've added the markercluster api to allow for clustering of 1800 markers.

The question I have now is how to fix the search autocomplete functionality that I had working before I added MarkerCluster code. Before I added that code the search existing places text box would zoom and center the map to the location that I selected.

I think I need to put the search code inside of the initialize script, but I'm not sure where.

[Search Code below]

$('#search_ex_places').blur(function(){//once the user has selected an existing place


  var marker = 0;
  var place = $(this).val();
  //initialize values
  var exists = 0;
  var lat = 0; 
  var lng = 0;
  $('#saved_places option').each(function(index){ //loop through the save places
    var cur_place = $(this).data('place'); //current place description

    //if current place in the loop is equal to the selected place
    //then set the information to their respected fields
    if(cur_place == place){ 
      exists = 1;
      $('#place_id').val($(this).data('id'));
      lat = $(this).data('lat');
      lng = $(this).data('lng');
      $('#n_place').val($(this).data('place'));
      $('#n_description').val($(this).data('description'));

    alert('lat: ' + lat + ', lng: ' + lng ); // aris put this alert here to see where             lat/lng values are at

      // map.setCenter(new google.maps.LatLng(lat,lng));  //set map center to the coordinates of the location
     //  map.setZoom(17); //set a custom zoom level of 17 
      //$('#map_canvas').gmap('get','map').setOptions({'center':(25.86568260193,-80.19351196289)});


var datcenter = new google.maps.LatLng(lat, lng);
        var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 17,
      center: datcenter,
      mapTypeId: google.maps.MapTypeId.ROADMAP

});
 var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: $(this).data('place')
});


    }
  });

  if(exists == 0){//if the place doesn't exist then empty all the text fields and hidden fields
    $('input[type=text], input[type=hidden]').val('');

  }else{
    //set the coordinates of the selected place
    var position = new google.maps.LatLng(lat, lng);

    //set marker position
    marker.setMap(map);
    marker.setPosition(position);

    //set the center of the map
     map.setCenter(marker.getPosition());
     map.setZoom(17);


  }
});

[end of search code]

High Above the search code I have this markercluster code working:

[code begins]

<script type="text/javascript">

// var src = 'https://developers.google.com/maps/tutorials/kml/westcampus.kml';

// var src = 'http://urgentcarepro.com/map/us_states.kml';



  function initialize() {
    var center = new google.maps.LatLng(37.4419, -122.1419);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });



var input = document.getElementById('search_new_places'); //get element to use as input for autocomplete
var autocomplete = new google.maps.places.Autocomplete(input); //set it as the input for autocomplete
autocomplete.bindTo('bounds', map); //bias the results to the maps viewport


    var markers = [];
    for (var i = 0; i < 1860; i++) {

    createMarker(i) ;
     }

     function createMarker(i) {

      var dataPhoto = data.photos[i];
      var latLng = new google.maps.LatLng(dataPhoto.latitude,
          dataPhoto.longitude);
      var marker = new google.maps.Marker({
        position: latLng,
        draggable: true, //make the marker draggable
        title: dataPhoto.photo_title , // title i guess
      });




 var contentString = '<div id="content" style="width:500px;">'+
  '<div id="siteNotice">'+
  '</div>'+
  '<h1 id="firstHeading" class="firstHeading">'+dataPhoto.photo_title+'</h1>'+
  '<div id="bodyContent">'+
  '<p><b>'+dataPhoto.photo_title+'</b>, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>'+
'<p>Visit website: <a href="#">'+
  'Click Here</a> '+
  '</p>'+
  '</div>'
  '</div>'; 

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



google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});   


//executed when a place is selected from the search field
google.maps.event.addListener(autocomplete, 'place_changed', function(){

    //get information about the selected place in the autocomplete text field
    var place = autocomplete.getPlace(); 

    if (place.geometry.viewport){ //for places within the default view port   (continents, countries)
      map.fitBounds(place.geometry.viewport); //set map center to the coordinates of the location
    } else { //for places that are not on the default view port (cities, streets)
      map.setCenter(place.geometry.location);  //set map center to the coordinates of the location
      map.setZoom(17); //set a custom zoom level of 17
    }

    marker.setMap(map); //set the map to be used by the  marker
    marker.setPosition(place.geometry.location); //plot marker into the coordinates of the location 

});


      markers.push(marker);

    }
     var markerCluster = new MarkerClusterer(map, markers);


  }


  function loadKmlLayer(src, map) {
 var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.description;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}



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



</script>

[code ends]

解决方案

The simplest fix it to make the map varialble global. Then use the global variable in your search function.

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 17,
  center: datcenter,
  mapTypeId: google.maps.MapTypeId.ROADMAP

});

To

map = new google.maps.Map(document.getElementById('map'), {
  zoom: 17,
  center: datcenter,
  mapTypeId: google.maps.MapTypeId.ROADMAP

});

Or remove those lines.

function initialize() {
  var center = new google.maps.LatLng(37.4419, -122.1419);

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
// rest of your initialize code

To:

// declare global map variable
var map = null;
function initialize() {
  var center = new google.maps.LatLng(37.4419, -122.1419);

  // initialize global map variable
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
// rest of your initialize code

这篇关于Google Maps API,搜索自动完成而不是缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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