2016-10-12 3 views
-1

У меня есть карта google с сотнями маркеров. Я хотел бы, чтобы карта была сосредоточена на местоположении пользователей - желательно нажатием кнопки. В настоящее время я сосредоточен на загрузке страницы, но с одной проблемой - он очищает все маркеры, когда он сосредоточен на местоположении. Я предполагаю, что это из-за того, как я вызываю скрипт. Идентификатор контейнера карты - 'map4'.google maps - центрирование по местоположению пользователя

Как я могу заставить этот скрипт работать без очистки существующих маркеров? Любая помощь будет принята с благодарностью.

<script> 
var map; // Google map object 

// Initialize and display a google map 
function Init() 
{ 
    // HTML5/W3C Geolocation 
    if (navigator.geolocation) 
     navigator.geolocation.getCurrentPosition(UserLocation); 
    // Default to Sherman Oaks 
    else 
     ShowLocation(38.8951, -77.0367, "Sherman Oaks, CA"); 
} 

// Callback function for asynchronous call to HTML5 geolocation 
function UserLocation(position) 
{ 
    ShowLocation(position.coords.latitude, position.coords.longitude, "This is your Location"); 
} 

// Display a map centered at the specified coordinate with a marker and InfoWindow. 
function ShowLocation(lat, lng, title) 
{ 
    // Create a Google coordinate object for where to center the map 
    var latlng = new google.maps.LatLng(lat, lng);  

    // Map options for how to display the Google map 
    var mapOptions = { zoom: 12, center: latlng }; 

    // Show the Google map in the div with the attribute id 'map-canvas'. 
    map = new google.maps.Map(document.getElementById('map4'), mapOptions); 

    // Place a Google Marker at the same location as the map center 
    // When you hover over the marker, it will display the title 
    var marker = new google.maps.Marker({ 
     position: latlng,  
     map: map,  
     title: title 
    }); 

    // Create an InfoWindow for the marker 
    var contentString = "<b>" + title + "</b>"; // HTML text to display in the InfoWindow 
    var infowindow = new google.maps.InfoWindow({ content: contentString }); 

    // Set event to display the InfoWindow anchored to the marker when the marker is clicked. 
    google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); 
} 

// Call the method 'Init()' to display the google map when the web page is displayed (load event) 
google.maps.event.addDomListener(window, 'load', Init); 

</script> 

ответ

1

Если я вас правильно понимаю, вы, кажется, уже создали карту, заселенный с маркерами, а затем вы хотите, чтобы центрировать ОЧЕНЬ ЖЕ карту. Если это так, необходимо изменить функцию ShowLocation(). Причина заключается в том, что эта линия

map = new google.maps.Map(document.getElementById('map4'), mapOptions); 

создает свежий новый экземпляр карты (замена какой-либо существующую карту в этом контейнере, при условии, если контейнер карты то же самое).

Итак, ваша проблема в том, что вы создаете и центрируете новую карту, а не просто центрируете старую.

Просто измените функцию центрирования для работы с существующей картой:

function ShowLocation(lat, lng, title , map) 
{ 
    // Create a Google coordinate object for where to center the map 
    var latlng = new google.maps.LatLng(lat, lng);  

    //Working with existing map instead of creating a new one 
    map.setCenter(latlng); 
    map.setZoom(12); 

    // Place a Google Marker at the same location as the map center 
    // When you hover over the marker, it will display the title 
    var marker = new google.maps.Marker({ 
     position: latlng,  
     map: map,  
     title: title 
    }); 

    // Create an InfoWindow for the marker 
    var contentString = "<b>" + title + "</b>"; // HTML text to display in the InfoWindow 
    var infowindow = new google.maps.InfoWindow({ content: contentString }); 

    // Set event to display the InfoWindow anchored to the marker when the marker is clicked. 
    google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); 
} 

И при вызове функции ShowLocation, это четвёртая параметр будет правильные google.maps.Map объекта, созданными при добавлении маркеров. Вы не можете ссылаться на карту только, зная, что она содержит элемент id, вам нужна ссылка на него.

+0

Ваши предположения верны! У меня есть существующая карта и вы хотите автоматически центрировать ее на месте пользователя - или предпочтительнее одним нажатием кнопки. – pioneer

+0

Итак, просто найдите где-нибудь в своем коде, где вы создаете исходную карту, к которой вы добавляете маркеры, например: 'map = new google.maps.Map (document.getElementById ('map4') ..' (но не в вашей функции «ShowLocation»). И тогда вы должны использовать тот же самый объект «map» с моей предоставленной функцией «ShowLocation» –

+0

Я пробовал код, но теперь он не центрируется на карте или не показывает местоположение пользователя. новая карта - так что это плюс. Возможно, я неправильно нахожу карту. Идентификатор должен быть «map4», но я не уверен, куда вводить эту информацию. – pioneer

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