0

KnockoutJS 라이브러리를 사용하는 간단한 Google지도 앱을 개발 중이거나 적어도 개념이 단순 해 보였습니다. KnockoutJS를 읽고 몇 가지 예제를 작성한 후 처음 부분을 정리했습니다. 지금까지의 html은 단지지도 일뿐입니다. 첫 번째 장애물을 극복하자마자 목록을 채우려합니다. 장애물은 Javascript에 있습니다.KnockoutJS의 ViewModel에서 전역 변수에 액세스 할 수 없습니다.

"use strict"; 

var map; 
var center; 
var defaultBounds; 
var placesServices; 

//LocationObject created to hold data for locations generated from google.places.nearbySearch 
var LocationObject = function(data){ 

    this.position = data.geometry.location; 
    this.lat = data.geometry.location.lat; 
    this.lng = data.geometry.location.lng; 
    this.name = data.name; 
    this.placeID = data.place_id; 
    this.rating = data.rating; 
    this.types = data.types; 
    this.linkToPhoto = data.html_attributions; 

}; 



function initMap(){ 

    map = new google.maps.Map(document.getElementById('map'), { 
     center: center, 
     zoom: 17, 
     mapTypeId: 'satellite', 
     draggable: true, 
     zoomControl: false, 
     scrollwheel: true, 
     disableDoubleClickZoom: true 
    }); 

    defaultBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(47.614217, -122.317981),new google.maps.LatLng(47.612975, -122.316291)); 
    map.fitBounds(defaultBounds); 

    placesServices = new google.maps.places.PlacesService(map); 

} 


    //ViewModel created to observe changes on the map 
var MapViewModel = function(){ 
    var self = this; 

    self.testarr = ko.observableArray([ 
     { firstName: 'Bert', lastName: 'Bertington' }, 
     { firstName: 'Charles', lastName: 'Charlesforth' }, 
     { firstName: 'Denise', lastName: 'Dentiste' } 
    ]); 

    self.locations = ko.observableArray([]); 
    self.markers = []; 

    this.getNearbyLocations = function(){ 
     if(placesServices === undefined){ 
      placesServices = new google.maps.places.PlacesService(map); 
     } 

     var request = { 
      location: center, 
      radius: getBoundsRadius(defaultBounds), 
      type: ['establishment'] 
     }; 

     placesServices.nearbySearch(request, function(results, status) { 
      if (status === google.maps.places.PlacesServiceStatus.OK) { 
       for (var i = 0; i <= 18; i++) { 
        var marker = new google.maps.Marker({ 
         map: map, 
         position: results[i].geometry.location, 
         animation: google.maps.Animation.DROP 
        }); 
        self.locations.push(new LocationObject(results[i])); 
        self.markers.push(marker); 
       } 
      } else{ 
       alert("We were not able to find any nearby locations in this Neighbourhood."); 
      } 
     }); 
    }; 

    this.init = function(){ 

     self.getNearbyLocations(); 

    }; 
}; 


var myMapViewModel = new MapViewModel(); 
myMapViewModel.init(); 
ko.applyBindings(myMapViewModel); 



/* Utility Functions */ 
function getBoundsRadius(bounds){....} 

오류는 다음과 같습니다 : 여기에 참조 코드입니다

Uncaught ReferenceError: google is not defined 
at MapViewModel.getNearbyLocations 

과 여기에 인식되지 왜 내가하지 않는이 때,지도 자체가로드 먼저는의를 얻으 문제없이 그러나 여기 전화를 끊다. 여기

참조에 대한 HTML이지만,이 문제가 안 : 나는 또한 당신의 app.js이지도 전에 호출되고 있기 때문에 오류가라고 생각

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <!-- Required meta tags --> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 

    <!-- Per Google guideline scheduled for the M65 release, css has been moved to an importer --> 
    <link rel="import" href="importer.htm"></link> 

    <!-- Bootstrap CSS --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> 


    </head> 
    <body> 
    <div class="container-fluid"> 
    <div class="row"> 
     <div class="col-xs-12 col-md-4"> 
      <!-- List goes in this column. --> 

      </div> 
     </div> 
     <div class="col-xs-12 col-md-8"> 
      <!-- Map goes into this column. --> 
      <div id="map" style="width:100%;height:100vh;"></div> 
     </div> 
     </div> 
    </div> 

<!-- jQuery first, then Popper.js, then Bootstrap JS --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> 
<!-- Optional JavaScript --> 
<script src="js/knockout.js" ></script> 
<script src="js/app.js"></script> 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC-1EdIyUOb74oGG_mEoPvJTAGCSJvSQms&callback=initMap&libraries=places"></script> 
</body> 

+0

시도 또한 체크 아웃 할 수 있습니다 app.js' – adiga

+0

'전에지도 스크립트 참조를 첨가 [이 질문에 대한 답변] (https://stackoverflow.com/questions/38627259/how-to-make-a-callback-to-google-maps-init-in-separate-files-of-a-web-app) – user3297291

답변

1

스크립트. 그러나 나는 그것을 변경하려고 시도, 동일한 오류, 그리고 또한 (user3297291의 의견에 의해 제안 된) async 매개 변수를 제거하려고했지만 여전히 같은 오류. 이론적으로는 should have worked입니다.

하지만이 일 - ready() 기능을 내부에 app.js 코드의 마지막 3 줄 바꿈 :

$(document).ready(function(){ 
    var myMapViewModel = new MapViewModel(); 
    myMapViewModel.init(); 
    ko.applyBindings(myMapViewModel); 
}); 
+0

그래, 나는 어제도 모든 대안을 테스트했다. 당신이 발견 한 것과 같은 결과였다. 또한지도가로드되어 전역 적으로 선언 된 변수에 저장되기 때문에 접근이 가능해야한다고 생각했습니다. 한 지점에서 각 함수에 변수를 전달할 구현을 시도했지만 동일한 결과가있었습니다. 나는 jquery 옵션을 오늘 밤에 추가하고 한번 승인을 승인 할 것이다. – aleksandar

+0

시간 초과로 랩핑하지 않으면 안되지 만, 나에게 충분히 가까이갔습니다. - 감사합니다! – aleksandar