심심한잉여의 잡동사니

세미프로젝트 - 네이버지도 현위치 구하기 Geolocation 본문

코딩일기/세미프로젝트

세미프로젝트 - 네이버지도 현위치 구하기 Geolocation

심심한잉여 2021. 11. 24. 21:14
반응형

navigator.geolocation은 VSCODE로만 사용했을 때 사용이 안되어서 사용 불가능한줄 알았지만

Chrome 50 버젼 이후로 HTTP 환경에서 사용이 불가능하게 되어 HTTPS 환경에서만 사용 가능 합니다.
또한 http://localhost 환경에서도 사용이 가능했다.

네이버 맵이 사용방법이 가장 잘 나와있어 네이버 맵을 예시로 들겠다.

var infowindow = new naver.maps.InfoWindow();

function onSuccessGeolocation(position) { //실행할 함수
    var location = new naver.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude);

    map.setCenter(location); // 지도의 중심을 어디로 잡을것인지 설정하는 코드
    map.setZoom(15); // 지도가 얼만큼 줌 되어있는지 설정하는 코드

    infowindow.setContent('<div style="padding:20px;">' + 'geolocation.getCurrentPosition() 위치' + '</div>');
	// 마커에 안내해줄 문구
    infowindow.open(map, location); 
    console.log('Coordinates: ' + location.toString());
}

function onErrorGeolocation() { // 오류 시 발생될 예외처리용 함수
    var center = map.getCenter();

    infowindow.setContent('<div style="padding:20px;">' +
        '<h5 style="margin-bottom:5px;color:#f00;">Geolocation failed!</h5>'+ "latitude: "+ center.lat() +"<br />longitude: "+ center.lng() +'</div>');

    infowindow.open(map, center);
}

$(window).on("load", function() { // 창이 실행되면 현 위치 값 구하는 함수 실행되는 제이쿼리
    if (navigator.geolocation) {
       
        navigator.geolocation.getCurrentPosition(onSuccessGeolocation, onErrorGeolocation);
    } else {
        var center = map.getCenter();
        infowindow.setContent('<div style="padding:20px;"><h5 style="margin-bottom:5px;color:#f00;">Geolocation not supported</h5></div>');
        infowindow.open(map, center);
    }
});

위 코드를 그대로 복사해서 script에 붙여넣었다.

근데 계속 현 위치 검색이 안되었기에 왜 안되는지 디버깅하는데 오래걸렸다.

이유는 바로 이클립스에서 제공하는 기본브라우저여서 였던 것. 해당 기능은 크롬을 기준으로 잡힌건지
크롬에서만 정상적인 작동을 했다.

이번 디버깅으로 인해 힘이 많이 빠지긴했는데 확실하게 깨닫게 된 것이 있다.

크롬을 통해 테스트를 해야한다는 것을 깨닫게 되었다.

반응형