레이블이 google map API인 게시물을 표시합니다. 모든 게시물 표시
레이블이 google map API인 게시물을 표시합니다. 모든 게시물 표시

2016년 11월 11일 금요일

2. 구글 지도 API로 가까운 매장 찾기 구현

이하 거리 구하기 서버 측 코드

asp + Msxml2.ServerXMLHTTP.6.0 사용 함.

의외로 간단~

<%
Session.CodePage = 65001
Response.ContentType = "application/json"
Response.Charset = "utf-8"


Dim callUrl 
Dim HttpReq
Dim params
origins = Request.QueryString("origins")
destinations = Request.QueryString("destinations")

callUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="&origins&"&destinations="&destinations&"&mode=transit&language=ko-KO&key=구글API키"
Set HttpReq = Server.CreateObject("Msxml2.ServerXMLHTTP.6.0")

HttpReq.open "GET", callUrl, False
HttpReq.send

Response.Write HttpReq.responseText
%>

1. 구글 지도 API로 가까운 매장 찾기 구현

이하 웹페이지 소스 일부. 뭐 내가 짠게 우왕 굿은 아니지만..

이래저래 잘 활용해 보시길...

script에 Google API 키 발급받아서 넣는거 잊지 말길...


var curPos = null;
var directionsDisplay = null;
var directionsService = null;
var storeList = new Array();
var findStoreFlag = false;
storeList[0] = {lat: 37.5707940, lng: 126.9710600};
storeList[1] = {lat: 37.5704049, lng: 126.9722485};
storeList[2] = {lat: 37.5060580, lng: 127.0033890};
storeList[3] = {lat: 37.4843585, lng: 126.9022739};
storeList[4] = {lat: 37.6505030, lng: 127.0619600};
storeList[5] = {lat: 37.3850110, lng: 127.1206630};
storeList[6] = {lat: 37.5544795, lng: 126.9366329};
storeList[7] = {lat: 37.6677905, lng: 126.7646956};
storeList[8] = {lat: 37.7525750, lng: 127.0690960};
function initMap() { 
 var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 14,
  center: storeList[0]
 });
 directionsDisplay = new google.maps.DirectionsRenderer;
 directionsService = new google.maps.DirectionsService; 
 directionsDisplay.setMap(map); 
 getLocation();
}

function getLocation() {  //위치 조회시작..

 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition,showError);
 } else {
  alert("Geolocation is not supported by this browser.");
  var map = new google.maps.Map(document.getElementById('map'), {
   zoom: 14,
   center: storeList[0]
  });
 }
}

function fnSetCurLoc(position){ // 현재 위치를 저장
 curPos = {
  lat: position.coords.latitude,
  lng: position.coords.longitude
 };
}

function showPosition(position) { 
 curPos = {
  lat: position.coords.latitude,
  lng: position.coords.longitude
 };
 alert(curPos);
 fnFindStore();//가까운 위치 미리 찾기...
 directionsService.route({
   origin:curPos,  // Haight.
   destination: storeList[document.getElementById('selStore').value],
   travelMode: google.maps.TravelMode.TRANSIT,
   unitSystem: google.maps.UnitSystem.METRIC,
   avoidHighways: false,
   avoidTolls: false
  }, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
   directionsDisplay.setDirections(response);
  } else {
   window.alert('Directions request failed due to ' + status);
  }
 });
}


var minDistance = 10000000;
var minDistInx = 0;
function fnFindStore(){
 if(!findStoreFlag){  //한번만 찾게 flag로 조정
  $.ajaxSetup({
   async: false
  });
 
  for(listCnt = 0 ; listCnt &lt; storeList.length ; listCnt ++){
   var callUrl = "/api/google/retDistance.asp";
   var sendParams = {  
    origins : curPos.lat + "," + curPos.lng, 
    destinations : storeList[listCnt].lat + "," + storeList[listCnt].lng
   };
   console.log(listCnt);
   $.getJSON( callUrl, sendParams ).done(function( data ) {
    console.log( "JSON Data: " + data.rows[0].elements[0].distance.value + ":::" + listCnt + ":::" + minDistInx + "::::" + minDistance);
    if(minDistance &gt; data.rows[0].elements[0].distance.value){    //최소 거리를 계산해서 저장...
     minDistance = data.rows[0].elements[0].distance.value;
     minDistInx = listCnt;
     console.log(minDistance);
     console.log(listCnt);
    }   
   }).fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
   });
  }
  
  if(!findStoreFlag) findStoreFlag = true;
 }
}

function fnSetStore(){
 console.log(minDistance);
 console.log(minDistInx);
 document.getElementById('selStore').value = minDistInx;
 directionsService.route({
   origin:curPos,  // Haight.
   destination: storeList[minDistInx],
   travelMode: google.maps.TravelMode.TRANSIT,
   unitSystem: google.maps.UnitSystem.METRIC,
   avoidHighways: false,
   avoidTolls: false
  }, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
   directionsDisplay.setDirections(response);
  } else {
   window.alert('Directions request failed due to ' + status);
  }
 });
}

function showError(error){
 switch (error.code){
  case error.PERMISSION_DENIED:
   alert("User denied the request for Geolocation.");
   break;
  case error.POSITION_UNAVAILABLE:
   alert("Location information is unavailable.");
   break;
  case error.TIMEOUT:
   alert("The request to get user location timed out.");
   break;
  case error.UNKNOWN_ERROR:
   alert("An unknown error occurred.");
   break;
 }
}

0. 구글 지도 API로 가까운 매장 찾기 구현

0. 회사에서 모바일 환경에서 매장으로 길찾기를 하게 해달라고 함.

1. 구글, 네이버, 다음 3개의 지도 서비스 검토

2. 일단 네이버, 다음은 제휴를 맺은 업체만 길찾기를 제공함.

   제휴가 없으면.. 그냥 지도에 점찍기 정도만 가능. 기타 기능은 서술 생략하겠음.

3. 구글은 길찾기를 무료로 제공하나!!!! 찾기 모드에서

   걷기, 자전거, 자가용... 모두!!!! 정상 작동하지 않는다..

   오직 대중교통 안내만 가능... 어쩔수 없이 이걸로 구현

   그나마 천만 다행인게 대중교통 안내에 도보 정보도 표시가 된다.

4. 기본 예제들은 구글 지도 API에서 제공

5. 개발한 부분은 현재 위치에서 각 매장들간의 거리를 측정하여

   데이터를 미리 갖고 있다가, 가까운 매장 검색 버튼을 눌렀을 때

   지도에 표기만 하면 됨.

6. 지도 API의 사용의 기본은 HTML5의 navigator.geolocation 를 사용하여

   접속 기기의 위도와 경도를 받아오는 것 부터 시작하면 된다.

7. 지도 그리는건 알아서들 하시고(https://developers.google.com/maps/web/?hl=ko)

   거리 측정에 대해서만 기술함.

8. 일단 길 찾기 class는 다음과 같다. 해당 class의 API와 예제를 참고하면

   길찾기를 간단히 구현 할 수 있다.

    var directionsDisplay = new google.maps.DirectionsRenderer;
    var directionsService = new google.maps.DirectionsService;

9. 가까운 지점의 검색은 distancematrix class를 사용한다.

   이 부분은 xml 또는 json 형태의 데이터를 수신하는 형식으로 사용 가능하다.

   xml은 parsing 하기 귀찮으므로 간단한 json 형태로 구현 하기로 했다.

10. 그런데.. 이 거리 구하는게 google에 실시간으로 통신을 해야 해서

   cross-domain 문제가 발생한다. 물론 jquery의 jsonp 형태의 통신을 하면

   일단 수신은 가능하나! 내 경우에 Unexpected Exception이 발생.

11. 이래저래 구글링을 해보았고, 내린 결론은

    수신되는 json 형식에 문제가 있다고 판단됨.

    뭐 엔터키를 치환해주면 된다는 글도 봤으나. 전부 안됨.

12. 방향 선회하여 json 통신으로 다시 개발.

13. 회사 개발 환경은 IIS 7.5 + ASP 환경으로 ASP에서 xml 통신을 사용하여

     위치 검색 결과를 수신하여 다시 웹페이지에서 json으로 받는 식으로 우회 함.

14. 개인적으로 cross-domain 문제 해결 할 시에 jquery로 다른 domain을

    호출하는 것 보다, Server에서 호출하면 쉽게 해결이 된다고 판단됨.

15. 여튼 구현 성공!


[낯선] 2026.06.20 이태원 MZK MuzikBar 공연

간만의 공연 이태원 비틀즈가 이전하여 MZK MuzikBar 로 새 단장 오픈을 한 뒤로 2번째 공연 새 베이시스트가 합류한 뒤로 첫 공연이기도 함.. 이래저래 틀린 부분도 많지만.. 그래도 간만에 그럭저럭 잘했다.. https://www.youtub...