본문 바로가기
javascript, jQuery/API

[javascript_api] geolocation으로 받은 위도,경도로 지도에 표시하기

by drCode 2020. 11. 26.
728x90
반응형

안녕하세요, 이번에는 지난 포스팅에 이어 geolocation api를 이용하여 얻은 위도, 경도로 지도상에 표현해보려고 합니다.

 

먼저 지난번에 이어서 geolocation navigator를 다시 사용하겠습니다.

<script>
	var latitude = "", longitude = "";
    
	window.onload = function() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(onSuccess, onError);
		} else {
			latitude = "", longitude = "";
		}	
	}
    
	function onSuccess(position) {
		latitude = position.coords.latitude;
		longitude = position.coords.longitude;
		makeMap(latitude, longitude);
	}
    
	function onError() {
		latitude ="33.450701";
		longitude = "126.570667";
		makeMap(latitude, longitude);
	}

	function makeMap(mylat, mylong) {
		if (document.getElementById("map")) {
			document.getElementById("map").innerHTML = "<iframe style=\"width: 400px; height: 400px\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"//maps.google.com/?ll=" + mylat + "," + mylong + "&z=16&output=embed\"></iframe>"; 
		}
	}
</script>
<body>
	<div id="map" style="width: 100%; height: 350px;"></div>
</body>

 

새로 추가된 코드는 makeMap 함수입니다.

위도와 경도를 받아서 iframe으로 구글맵 지도를 보여줍니다.

원래는 카카오맵 API를 사용하여 보여드리려 했으나,

실제로 서비스하는 홈페이지가 아닌, 블로그 상으로 띄우려해서 그런지 api 호출이 되질 않는 것 같습니다. 

 

그러면 지도를 확인해보겠습니다.

 

 

 
728x90
반응형

댓글