2013-11-06 4 views
1

Я просматривал и работал с примером локатора хранилища API Карт Google, который использует API мест. Я добавил markkerluster api для кластеризации 1800 маркеров.API Карт Google, поиск автозаполнения не масштабируется

Вопрос, который у меня есть, заключается в том, как исправить функциональность автозаполнения поиска, с которой я работал, прежде чем добавить код MarkerCluster. Прежде чем я добавлю этот код, текстовое поле поиска существующих мест будет масштабировать и центрировать карту в выбранное мной местоположение.

Я думаю, мне нужно поместить код поиска внутри скрипта initialize, но я не уверен, где.

[Поиск Код ниже]

$('#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); 


    } 
}); 

[конец поиска кода]

высоко над поисковой кода у меня есть этот 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'; 



    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> 

[код заканчивается]

ответ

1

Простейшее исправление, чтобы сделать карту varialble глобальной. Затем используйте глобальную переменную в вашей функции поиска.

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 
    }); 
// 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 
+0

Большое спасибо за вашу помощь! @geocodezip Ваши предложения были большой помощью, поскольку они помогли мне найти ошибки, вызывающие конкретную проблему, которую я испытывал. На самом деле мне пришлось включить фрагмент кода автозаполнения javascript в моей функции «intialize», чтобы получить масштабирование, чтобы начать работать снова. Однако теперь карта занимает много времени, чтобы загружать и перезагружать между пользовательскими событиями. Любые мысли о том, как я могу ускорить процесс. Еще раз спасибо! – alex

Смежные вопросы