2014-02-05 3 views
1

페이지에 'center'버튼을 추가해야합니다. 클릭하면지도가 setCenter 메소드를 사용하여 핀 중심에 배치됩니다. 그러나 내 버튼을 클릭하면지도를 표시하는 대신지도가 비어있게됩니다.Google지도 API setCenter 메소드가 작동하지 않습니다.

이것은 내 코드입니다.

어떻게 문제를 해결할 수 있습니까? 미리 감사드립니다.

<script src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script> 
    function init() { 
    var addButton = document.getElementById("setcenter"); 
    addButton.onclick = handleSetCenterButtonClicked; 
    getMyLocation(); 
    } 


    window.onload = init; 

    function getMyLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(displayLocation); 
    } else { 
     alert("Oops, no geolocation support"); 
    } 
    } 

    function displayLocation(position) { 
    showMap(position.coords); 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    var div = document.getElementById("location"); 
    div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude; 
    } 

    var map; 
    function showMap(coords) { 
    var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude); 
    var mapOptions = { 
     zoom : 18, 
     center : googleLatAndLong, 
     mapTypeId : google.maps.MapTypeId.SATELLITE 
    }; 
    var mapDiv = document.getElementById("map"); 
    map = new google.maps.Map(mapDiv, mapOptions); 

    addMarker(googleLatAndLong); 
    } 

    var marker; 
    var markerArray = new Array(); 

    function addMarker(latLong) { 
    var markerOptions = { 
     position : latLong, 
     map : map 
    }; 
    marker = new google.maps.Marker(markerOptions); 

    markerArray.push(marker); 
    } 

    // this is my setCenter method function 
    function handleSetCenterButtonClicked(coords) { 

    var latLng = new google.maps.LatLng(coords.latitude, coords.lotitude); 
    map.setCenter(latLng); 
    } 

    // this is my setCenter method function 
</script> 

답변

5

문제는 귀하의 기능에 있습니다 (오타 이외) :

function handleSetCenterButtonClicked(coords) { 

    var latLng = new google.maps.LatLng(coords.latitude, coords.lotitude); 
    map.setCenter(latLng); 
    } 

클릭하면 coords은 lat/lng에 대한 정보가없는 MouseEvent입니다. google api에서 MouseEvent과 같지 않습니다. 센터에 설정할 값이 무엇인지는 분명하지 않습니다. 내 페이지를 연 사용자의 위치를 ​​알려면? 아니면 다른 값으로?

그는 전역 변수를 추가 할 수 있습니다 주위에 드래그 한 후 사용자의 위치에 중심을 배치하려면 다음 기능 showMap()에서

var yourPos; 

알려진 값으로 설정 :

yourPos = googleLatAndLong; 

을 그리고 그것을 사용 클릭 핸들러 :

function handleSetCenterButtonClicked(coords) { 

    //var latLng = new google.maps.LatLng(coords.lat(), coords.lng()); 
    //map.setCenter(latLng); 

    map.setCenter(yourPos); 
    } 

그 외에도 케이스 처리가 없습니다 사용자가 자신의 위치를 ​​공유하고 싶지 않은 경우

+0

대단히 감사합니다. 많은 의미가 있습니다. – Rui

1

나는 코드가 잘못 생각 :

var latLng = new google.maps.LatLng(coords.latitude, coords.lotitude); 

그것은해야한다 :

var latLng = new google.maps.LatLng(coords.latitude, coords.longitude); 

기능 handleSetCenterButtonClicked (좌표)에서 -하지 "좌표"를 coords.longitude "입니다. 제비 "

관련 문제