Google Maps API, search autocomplete not zooming

2019-06-07 15:17发布

问题:

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]

回答1:

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