2015-04-06 3 views
-1

Im работает с картами Google, поэтому все мое приложение в основном представляет собой большие карты google. Это JS-код у меня есть, на мой взгляд:structuring js code wrong

  <script> 
     $(document).ready(function() { 
      var window = $("#mapWindow").data("kendoWindow"); 
      window.center(); 
      console.log('@Request.IsAuthenticated'); 
      if ('@Request.IsAuthenticated' == 'False') { 
       getLoginContent(); 
       console.log("False"); 
      } 
      if ('@SessionStore.CurrentBlogId' == 0 && '@Request.IsAuthenticated' == 'True') { 
       getNewBlogContent(); 
       console.log("Blogid 0 and true"); 
      } 
      if ('@SessionStore.CurrentBlogId' > 0 && '@Request.IsAuthenticated' == 'True') { 
       getDestinations(); 
       console.log("Blogid > 0 true"); 
      } 


      console.log('@SessionStore.CurrentBlogId'); 

      function getNewBlogContent() { 
       $.ajax({ 
        url: '@Url.Action("NewBlog", "Home")', 
        type: 'GET', 
        dataType: 'html', 
        cache: false, 
        success: function (data) { 
         $("#mapWindow").html(data); 
         window.title("Create Blog"); 
         window.open(); 
        }, 
        error: function (xhr, error) { 
        }, 
       }); 
      } 


      function getLoginContent() { 
       $.ajax({ 
        url: '@Url.Action("Login", "Account")', 
        type: 'GET', 
        dataType: 'html', 
        cache: false, 
        success: function(data) { 
         $("#mapWindow").html(data); 
         window.title("Login"); 
         window.open(); 
        }, 
        error: function(xhr, error) { 
        }, 
       }); 
      } 

      function getDestinations() { 
       $.ajax({ 
        url: '@Url.Action("GetDestinations", "Home")', 
        type: 'POST', 
        dataType: 'JSON', 
        cache: false, 
        success: function (data) { 
         console.log(data); 
         for (destination in data) { 
          console.log(data[destination]); 
          var latlng = { lat: data[destination].Latitude, lng: data[destination].Longitude } 
          console.log(latlng); 
          console.log(map); 
          var marker = new google.maps.Marker({ 
           map: map, 
           postion: new google.maps.LatLng(latlng.lat, latlng.lng), 
          }); 


          marker.setIcon(/** {google.maps.Icon} */({ 
           url: '/Content/Markers/green_MarkerX.png', 
           size: new google.maps.Size(71, 71), 
           origin: new google.maps.Point(0, 0), 
           anchor: new google.maps.Point(17, 34), 
           scaledSize: new google.maps.Size(35, 35) 
          })); 
          marker.setPosition(latlng); 
          marker.setVisible(true); 
         } 
        }, 
        error: function (xhr, error) { 
         console.log(error); 
        }, 
       }); 
      } 


     }); 
    </script> 

и поскольку есть некоторый код, который я не могу положить в JS-файла, как @sessionstore переменной и @ request.isauthenticated свойств я не могу переместите этот код в js-файл.

Тогда у меня есть свой Google Maps код в JS-файла, как это:

 var map; 

function initialize() { 
    var mapCanvas = document.getElementById('map-canvas'); 
    var mapOptions = { 
     center: new google.maps.LatLng(0, 0), 
     zoom: 4, 
     mapTypeId: google.maps.MapTypeId.SATELLITE 
    } 
    map = new google.maps.Map(mapCanvas, mapOptions); 


    var input = document.getElementById('geoAutocomplete'); 
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); 

    var autocomplete = new google.maps.places.Autocomplete(input); 
    autocomplete.bindTo('bounds', map); 

    var infowindow = new InfoBubble({ 
     map: map, 
     position: new google.maps.LatLng(-32.0, 149.0), 
     shadowStyle: 1, 
     padding: 0, 
     backgroundColor: 'rgb(57,57,57)', 
     borderRadius: 5, 
     arrowSize: 10, 
     borderWidth: 1, 
     borderColor: '#2c2c2c', 
     disableAutoPan: true, 
     hideCloseButton: true, 
     arrowPosition: 30, 
     backgroundClassName: 'transparent', 
     arrowStyle: 2 
    }); 


    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
     infowindow.close(); 
     var marker = new google.maps.Marker({ 
      map: map, 
      anchorPoint: new google.maps.Point(0, -29), 
     }); 

     marker.setVisible(false); 
     var place = autocomplete.getPlace(); 
     console.log(place); 
     if (!place.geometry) { 
      return; 
     } 


     // If the place has a geometry, then present it on a map. 
     if (place.geometry.viewport) { 
      map.fitBounds(place.geometry.viewport); 
     } else { 
      map.setCenter(place.geometry.location); 
      map.setZoom(17); // Why 17? Because it looks good. 
     } 
     marker.setIcon(/** @type {google.maps.Icon} */({ 
      url: '/Content/Markers/green_MarkerX.png', 
      size: new google.maps.Size(71, 71), 
      origin: new google.maps.Point(0, 0), 
      anchor: new google.maps.Point(17, 34), 
      scaledSize: new google.maps.Size(35, 35) 
     })); 
     console.log("position: " + place.geometry.location); 
     marker.setPosition(place.geometry.location); 
     marker.setVisible(true); 

     var address = ''; 
     if (place.address_components) { 
      address = [ 
       (place.address_components[0] && place.address_components[0].short_name || ''), 
       (place.address_components[1] && place.address_components[1].short_name || ''), 
       (place.address_components[2] && place.address_components[2].short_name || '') 
      ].join(' '); 
     } 

     infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address); 
     infowindow.open(map, marker); 
     var longitude = place.geometry.location.D.toFixed(2); 
     var latitude = place.geometry.location.k.toFixed(2); 

     var countryIndex = place.address_components.length - 1; 
     $.ajax({ 
      url: '/Home/AddDestination', 
      type: 'POST', 
      dataType: 'html', 
      cache: false, 
      data:{ 
       destinationName: place.name, 
       countryCode: place.address_components[countryIndex].short_name, 
       continentCode: getContinent(place.address_components[countryIndex].short_name), 
       longitude: longitude.replace(".", ","), 
       latitude: latitude.replace(".", ",") 
    }, 
      success: function (data) { 
       console.log(data); 
      }, 
      error: function (xhr, error) { 
      }, 
     }); 
    }); 
} 

google.maps.event.addDomListener(window, 'load', initialize); 

Так что мои проблемы в том, что во взгляде-JS кода у меня есть метод, который получает все сохраненные места назначения в от и я хочу, чтобы он помещал маркер на карту для каждого из них. Таким образом, в GetDestination() я хочу, чтобы поставить маркер на карте с помощью этого кода:

var marker = new google.maps.Marker({ 
           map: map, 
           postion: new google.maps.LatLng(latlng.lat, latlng.lng), 
          }); 

проблема в том, что карта еще не создана. Он создается в js-файле. Как я могу структурировать это лучше, чтобы я мог выполнить метод getdestination после создания карты?

+0

Включите код в функцию и вызовите функцию при создании карты? – epascarello

ответ

1

На ваш взгляд JS, отредактируйте ваш getDestinations function. Переместить if инструкция в функцию.

function getDestinations() { 
    if ('@SessionStore.CurrentBlogId' > 0 && '@Request.IsAuthenticated' == 'True') { 
     console.log("Blogid > 0 true"); 

     $.ajax({ 
      url: '@Url.Action("GetDestinations", "Home")', 
      type: 'POST', 
      dataType: 'JSON', 
      cache: false, 
      success: function (data) { 
       console.log(data); 
       for (destination in data) { 
        console.log(data[destination]); 
        var latlng = { lat: data[destination].Latitude, lng: data[destination].Longitude } 
        console.log(latlng); 
        console.log(map); 
        var marker = new google.maps.Marker({ 
         map: map, 
         postion: new google.maps.LatLng(latlng.lat, latlng.lng), 
        }); 


        marker.setIcon(/** {google.maps.Icon} */({ 
         url: '/Content/Markers/green_MarkerX.png', 
         size: new google.maps.Size(71, 71), 
         origin: new google.maps.Point(0, 0), 
         anchor: new google.maps.Point(17, 34), 
         scaledSize: new google.maps.Size(35, 35) 
        })); 
        marker.setPosition(latlng); 
        marker.setVisible(true); 
       } 
      }, 
      error: function (xhr, error) { 
       console.log(error); 
      }, 
     }); 
    } 
} 

В файле Google Maps JS добавить в инициализировать функцию.

google.maps.event.addListenerOnce(map, 'idle', function(){ 
    // Get destinations after maps is loaded 
    getDestinations(); 
}); 

Если idle событие dosen't работы, попробуйте tilesloaded событие.