2017-08-28 8 views
-2

私は旅行セールスマンの問題を解決しようとしてイオンアプリケーションを作成しています。 getMarker()を使用してjsonファイルから場所の緯度と経度を取得します。ionicを使用してトラベリングセールスマンを解決する:プロパティを読み取ることができませんundefined

getMarkers() { 
this.http.get('assets/data/markers.json') 
.map((res) => res.json()) 
.subscribe(data => { 
    this.addMarkersToMap(data); 
}); 

}

とaddMArkersToMap()は、Googleマップにこれらのマーカーを配置します。これらの位置の緯度と経度を配列ノードに配置します。

enter code here addMarkersToMap(markers) { 
for(let marker of markers) { 
    let position = new google.maps.LatLng(marker.latitude, marker.longitude); 
    console.log(position); 
this.nodes.push(position); 
    console.log(this.nodes); 

    var markerposition = new google.maps.Marker({position: position, title: marker.title}); 
    markerposition.setMap(this.map); 
} 

}私はコードhere

私は問題を得続けるimage of the error

home.ts使用TSP解決するために遺伝的アルゴリズムを使用して

IM:431キャッチされない例外TypeErrorを:プロパティを読み取ることができません。 'ga' of undefined

この問題を解決するにはどうすればいいですか?ここ

は私のコードのコメントとして

import { Component, ViewChild, ElementRef } from '@angular/core'; 
 
import { NavController } from 'ionic-angular'; 
 
import { Http } from '@angular/http'; 
 
import 'rxjs/add/operator/map'; 
 

 
declare var google; 
 

 
@Component({ 
 
    selector: 'page-home', 
 
    templateUrl: 'home.html' 
 
}) 
 

 

 
export class HomePage { 
 
// let map:any; 
 
    
 

 

 
    @ViewChild('mapContainer') mapContainer: ElementRef; 
 

 
    map: any ; 
 
    directionsDisplay: any ; 
 
    directionService:any ; 
 
    polylinePath; 
 
    
 
    nodes: Array<any>=[] 
 
    prevNodes:Array<any>=[] ; 
 
    markers:Array<any>=[] ; 
 
    duration:Array<any>=[] ; 
 
    service = new google.maps.DistanceMatrixService(); 
 
    constructor(public navCtrl: NavController, public http: Http,) { 
 
    
 
    } 
 

 

 
    ionViewWillEnter() { 
 

 
    this.displayGoogleMap(); 
 
    this.getMarkers(); 
 

 

 

 
    // this.getDuration(); 
 
    this.nodes; 
 
    this.duration; 
 
    } 
 

 

 
//initialize google maps 
 
    displayGoogleMap() { 
 
    let latLng = new google.maps.LatLng(14.5507592 , 121.049493); 
 

 
    let mapOptions = { 
 
     center: latLng, 
 
     disableDefaultUI: true, 
 
     zoom: 15, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
 
     //styles: [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#000000"},{"lightness":40}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#000000"},{"lightness":16}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":17},{"weight":1.2}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#15191b"}]},{"featureType":"landscape.man_made","elementType":"geometry.stroke","stylers":[{"color":"#2f373a"},{"visibility":"on"}]},{"featureType":"landscape.natural.landcover","elementType":"geometry.fill","stylers":[{"color":"#15191b"}]},{"featureType":"landscape.natural.landcover","elementType":"geometry.stroke","stylers":[{"color":"#15191b"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#15191b"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry.stroke","stylers":[{"visibility":"on"},{"color":"#15191b"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":21}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"visibility":"off"},{"color":"#f45454"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#ad2b2b"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#eaeaea"},{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#15e181"},{"lightness":17},{"visibility":"on"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":18}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#8095a0"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":16}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#8095a0"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":19}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#0f252e"},{"lightness":17}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#364350"}]}] 
 
     
 
    } 
 
    this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions); 
 
    } 
 

 

 

 

 

 
    getMarkers() { 
 
    this.http.get('assets/data/markers.json') 
 
    .map((res) => res.json()) 
 
    .subscribe(data => { 
 
     this.addMarkersToMap(data); 
 
    }); 
 
    } 
 

 

 

 
    
 
    addMarkersToMap(markers) { 
 
    for(let marker of markers) { 
 
     let position = new google.maps.LatLng(marker.latitude, marker.longitude); 
 
     console.log(position); 
 
    this.nodes.push(position); 
 
     console.log(this.nodes); 
 
     
 
     var markerposition = new google.maps.Marker({position: position, title: marker.title}); 
 
     markerposition.setMap(this.map); 
 
    } 
 
    
 
    } 
 

 

 
    ga = { 
 
    // Default config 
 
    "crossoverRate": 0.5, 
 
    "mutationRate": 0.1, 
 
    "populationSize": 50, 
 
    "tournamentSize": 5, 
 
    "elitism": true, 
 
    "maxGenerations": 50, 
 
    
 
    "tickerSpeed": 60, 
 

 
    // Loads config from HTML inputs 
 
    // "getConfig": function() { 
 
    //  crossoverRate = 0.5; 
 
    //  this.ga.mutationRate = 0.1; 
 
    //  this.ga.populationSize =50; 
 
    //  this.ga.elitism =true; 
 
    //  this.ga.maxGenerations =50; 
 
    // }, 
 
    
 
    // Evolves given population 
 
    "evolvePopulation": function(population, generationCallBack, completeCallBack) {   
 
     // Start evolution 
 
     var generation = 1; 
 
     var evolveInterval = setInterval(function() { 
 
      if (generationCallBack != undefined) { 
 
       generationCallBack({ 
 
        population: population, 
 
        generation: generation, 
 
       }); 
 
      } 
 

 
      // Evolve population 
 
      population = population.crossover(); 
 
      population.mutate(); 
 
      generation++; 
 
      
 
      // If max generations passed 
 
      if (generation > this.ga.maxGenerations) { 
 
       // Stop looping 
 
       clearInterval(evolveInterval); 
 
       
 
       if (completeCallBack != undefined) { 
 
        completeCallBack({ 
 
         population: population, 
 
         generation: generation, 
 
        }); 
 
       } 
 
      } 
 
     }, this.ga.tickerSpeed); 
 
    }, 
 

 
    // Population class 
 
    "population": function() { 
 
     // Holds individuals of population 
 
     this.individuals = []; 
 
    
 
     // Initial population of random individuals with given chromosome length 
 
     this.initialize = function(chromosomeLength) { 
 
      this.individuals = []; 
 
    
 
      for (var i = 0; i < this.ga.populationSize; i++) { 
 
       var newIndividual = new this.ga.individual(chromosomeLength); 
 
       newIndividual.initialize(); 
 
       this.individuals.push(newIndividual); 
 
      } 
 
     }; 
 
     
 
     // Mutates current population 
 
     this.mutate = function() { 
 
      var fittestIndex = this.getFittestIndex(); 
 

 
      for (let index in this.individuals) { 
 
       // Don't mutate if this is the elite individual and elitism is enabled 
 
       if (this.ga.elitism != true || index != fittestIndex) { 
 
        this.individuals[index].mutate(); 
 
       } 
 
      } 
 
     }; 
 

 
     // Applies crossover to current population and returns population of offspring 
 
     this.crossover = function() { 
 
      // Create offspring population 
 
      var newPopulation = new this.ga.population(); 
 
      
 
      // Find fittest individual 
 
      var fittestIndex = this.getFittestIndex(); 
 

 
      for (let index in this.individuals) { 
 
       // Add unchanged into next generation if this is the elite individual and elitism is enabled 
 
       if (this.ga.elitism == true && index == fittestIndex) { 
 
        // Replicate individual 
 
        var eliteIndividual = new this.ga.individual(this.individuals[index].chromosomeLength); 
 
        eliteIndividual.setChromosome(this.individuals[index].chromosome.slice()); 
 
        newPopulation.addIndividual(eliteIndividual); 
 
       } else { 
 
        // Select mate 
 
        var parent = this.tournamentSelection(); 
 
        // Apply crossover 
 
        this.individuals[index].crossover(parent, newPopulation); 
 
       } 
 
      } 
 
      
 
      return newPopulation; 
 
     }; 
 

 
     // Adds an individual to current population 
 
     this.addIndividual = function(individual) { 
 
      this.individuals.push(individual); 
 
     }; 
 

 
     // Selects an individual with tournament selection 
 
     this.tournamentSelection = function() { 
 
      // Randomly order population 
 
      for (var i = 0; i < this.individuals.length; i++) { 
 
       var randomIndex = Math.floor(Math.random() * this.individuals.length); 
 
       var tempIndividual = this.individuals[randomIndex]; 
 
       this.individuals[randomIndex] = this.individuals[i]; 
 
       this.individuals[i] = tempIndividual; 
 
      } 
 

 
      // Create tournament population and add individuals 
 
      var tournamentPopulation = new this.ga.population(); 
 
      for (var i = 0; i < this.ga.tournamentSize; i++) { 
 
       tournamentPopulation.addIndividual(this.individuals[i]); 
 
      } 
 

 
      return tournamentPopulation.getFittest(); 
 
     }; 
 
     
 
     // Return the fittest individual's population index 
 
     this.getFittestIndex = function() { 
 
      var fittestIndex = 0; 
 

 
      // Loop over population looking for fittest 
 
      for (var i = 1; i < this.individuals.length; i++) { 
 
       if (this.individuals[i].calcFitness() > this.individuals[fittestIndex].calcFitness()) { 
 
        fittestIndex = i; 
 
       } 
 
      } 
 

 
      return fittestIndex; 
 
     }; 
 

 
     // Return fittest individual 
 
     this.getFittest = function() { 
 
      return this.individuals[this.getFittestIndex()]; 
 
     }; 
 
    }, 
 

 
    // Individual class 
 
    "individual": function(chromosomeLength) { 
 
     this.chromosomeLength = chromosomeLength; 
 
     this.fitness = null; 
 
     this.chromosome = []; 
 

 
     // Initialize random individual 
 
     this.initialize = function() { 
 
      this.chromosome = []; 
 

 
      // Generate random chromosome 
 
      for (var i = 0; i < this.chromosomeLength; i++) { 
 
       this.chromosome.push(i); 
 
      } 
 
      for (var i = 0; i < this.chromosomeLength; i++) { 
 
       var randomIndex = Math.floor(Math.random() * this.chromosomeLength); 
 
       var tempNode = this.chromosome[randomIndex]; 
 
       this.chromosome[randomIndex] = this.chromosome[i]; 
 
       this.chromosome[i] = tempNode; 
 
      } 
 
     }; 
 
     
 
     // Set individual's chromosome 
 
     this.setChromosome = function(chromosome) { 
 
      this.chromosome = chromosome; 
 
     }; 
 
     
 
     // Mutate individual 
 
     this.mutate = function() { 
 
      this.fitness = null; 
 
      
 
      // Loop over chromosome making random changes 
 
      for (let index in this.chromosome) { 
 
       if (this.ga.mutationRate > Math.random()) { 
 
        var randomIndex = Math.floor(Math.random() * this.chromosomeLength); 
 
        var tempNode = this.chromosome[randomIndex]; 
 
        this.chromosome[randomIndex] = this.chromosome[index]; 
 
        this.chromosome[index] = tempNode; 
 
       } 
 
      } 
 
     }; 
 
     
 
     // Returns individuals route distance 
 
     this.getDistance = function() { 
 
      var totalDistance = 0; 
 

 
      for (let index in this.chromosome) { 
 
       var startNode = this.chromosome[index]; 
 
       var endNode = this.chromosome[0]; 
 
       if ((parseInt(index) + 1) < this.chromosome.length) { 
 
        endNode = this.chromosome[(parseInt(index) + 1)]; 
 
       } 
 

 
       totalDistance += this.durations[startNode][endNode]; 
 
      } 
 
      
 
      totalDistance += this.durations[startNode][endNode]; 
 
      
 
      return totalDistance; 
 
     }; 
 

 
     // Calculates individuals fitness value 
 
     this.calcFitness = function() { 
 
      if (this.fitness != null) { 
 
       return this.fitness; 
 
      } 
 
     
 
      var totalDistance = this.getDistance(); 
 

 
      this.fitness = 1/totalDistance; 
 
      return this.fitness; 
 
     }; 
 

 
     // Applies crossover to current individual and mate, then adds it's offspring to given population 
 
     this.crossover = function(individual, offspringPopulation) { 
 
      var offspringChromosome = []; 
 

 
      // Add a random amount of this individual's genetic information to offspring 
 
      var startPos = Math.floor(this.chromosome.length * Math.random()); 
 
      var endPos = Math.floor(this.chromosome.length * Math.random()); 
 

 
      var i = startPos; 
 
      while (i != endPos) { 
 
       offspringChromosome[i] = individual.chromosome[i]; 
 
       i++ 
 

 
       if (i >= this.chromosome.length) { 
 
        i = 0; 
 
       } 
 
      } 
 

 
      // Add any remaining genetic information from individual's mate 
 
      for (let parentIndex in individual.chromosome) { 
 
       var node = individual.chromosome[parentIndex]; 
 

 
       var nodeFound = false; 
 
       for (let offspringIndex in offspringChromosome) { 
 
        if (offspringChromosome[offspringIndex] == node) { 
 
         nodeFound = true; 
 
         break; 
 
        } 
 
       } 
 

 
       if (nodeFound == false) { 
 
        for (var offspringIndex = 0; offspringIndex < individual.chromosome.length; offspringIndex++) { 
 
         if (offspringChromosome[offspringIndex] == undefined) { 
 
          offspringChromosome[offspringIndex] = node; 
 
          break; 
 
         } 
 
        } 
 
       } 
 
      } 
 

 
      // Add chromosome to offspring and add offspring to population 
 
      var offspring = new this.ga.individual(this.chromosomeLength); 
 
      offspring.setChromosome(offspringChromosome); 
 
      offspringPopulation.addIndividual(offspring); 
 
     }; 
 
    }, 
 
} 
 

 

 

 
    
 
//get all duration depending on the travel type 
 
getDuration(callback){ 
 
    var service = new google.maps.DistanceMatrixService(); 
 
    service.getDistanceMatrix({ 
 
     origins: this.nodes, 
 
     destinations: this.nodes, 
 
     travelMode: 'DRIVING', 
 
     avoidHighways: false, 
 
     avoidTolls: false, 
 
    }, function(distanceData) { 
 
    // Create duration data array 
 
    let nodeDistanceData; 
 
    for (let originNodeIndex in distanceData.rows) { 
 
     nodeDistanceData = distanceData.rows[originNodeIndex].elements; 
 
     if(nodeDistanceData != null){ 
 
      this.durations.push(nodeDistanceData) ; 
 
     } 
 
     
 
     console.log(this.duration); 
 
     for (let destinationNodeIndex in nodeDistanceData) { 
 
      // if (this.durations[originNodeIndex][destinationNodeIndex] = nodeDistanceData[destinationNodeIndex].duration == undefined) { 
 
      //  alert('Error: couldn\'t get a trip duration from API'); 
 
      //  return; 
 
      // } 
 
      this.durations[originNodeIndex][destinationNodeIndex] = nodeDistanceData[destinationNodeIndex].duration.value; 
 
     } 
 
    } 
 
    if (callback != undefined) { 
 
     callback(); 
 
    } 
 
}); 
 

 

 
} 
 

 

 

 

 
//Startt GA 
 

 
ionViewDidLoad(){ 
 

 
    function GA(){ 
 
    if(this.prevNodes.length >=2){ 
 
    this.nodes = this.prevNodes; 
 
}else{ 
 
    return; 
 
    } 
 
} 
 

 

 
if (this.directionsDisplay != null){ 
 
    this.directionsDisplay.setMap(null); 
 
    this.directionsDisplay =null; 
 

 
} 
 

 

 
    //Get route Direction 
 

 

 

 
this.getDuration(function(){ 
 
    //get config and create initial GA population 
 
    this.ga.getConfig(); 
 
    let pop = this.ga.population(); 
 
    pop.Initialize(this.nodes.length); 
 
    let route =pop.getFittest().chromosome; 
 

 
    this.ga.evolvePopulation(pop, function(update){ 
 
    update.generation; 
 
    (update.population.getFittest().getDistance() /60).toFixed(2); 
 
    // Get route coordinates 
 
    var route = update.population.getFittest().chromosome; 
 
    var routeCoordinates = []; 
 
    for (let index in route) { 
 
     routeCoordinates[index] = this.nodes[route[index]]; 
 
    } 
 
    
 
    routeCoordinates[route.length] = this.nodes[route[0]]; 
 
    
 
    // Display temp. route 
 
    if (this.polylinePath != undefined) { 
 
    this.polylinePath.setMap(null); 
 
    } 
 
    this.polylinePath = new google.maps.Polyline({ 
 
    path: routeCoordinates, 
 
    strokeColor: "#0066ff", 
 
    strokeOpacity: 0.75, 
 
    strokeWeight: 2, 
 
    }); 
 
    this.polylinePath.setMap(this.map); 
 

 
    }, function(result){ 
 
// Get route 
 
route = result.population.getFittest().chromosome; 
 

 
    // Add route to map 
 
this.directionsService = new google.maps.DirectionsService(); 
 
this.directionsDisplay = new google.maps.DirectionsRenderer(); 
 
this.directionsDisplay.setMap(this.map); 
 
var waypts = []; 
 
for (var i = 1; i < route.length; i++) { 
 
waypts.push({ 
 
location: this.nodes[route[i]], 
 
stopover: true 
 
}); 
 
} 
 

 
console.log(waypts); 
 
// Add final route to map 
 
var request = { 
 
    origin: this.nodes[route[0]], 
 
destination: this.nodes[route[0]], 
 
waypoints: waypts, 
 
travelMode: google.maps.TravelMode["Driving"], 
 
avoidHighways: true, 
 
avoidTolls: false 
 
};     
 
this.directionsService.route(request, function(response, status){ 
 
    if(status ==google.maps.DirectionsStatus.OK){ 
 
     this.directionsDisplay.setDirections(response); 
 
    } 
 
    }); 
 
}); 
 

 

 

 
}); 
 

 
} 
 

 
}
<ion-header> 
 
    <ion-navbar> 
 
    <ion-title> 
 
     STUFF 
 
    </ion-title> 
 
    </ion-navbar> 
 
</ion-header> 
 

 
<ion-content padding> 
 
    <div #mapContainer id="map"></div> 
 
</ion-content>

+3

グッドニュース:あなたはこのような何かにその構造を変更する必要が

export class HomePage() { // .... ionViewDidLoad(){ // 'this.ga' is called here, 'this.ga' will throw the error since it is not the property of 'HomePage' } } var ga = { // .... }; 

は現在、これはあなたのコードの構造です。 – Marty

+1

これはランタイムエラーです。 JSと同じように起こるでしょう。 – Thilo

答えて

1

でこう述べています。

@Marty:、 と@Thilo "Javascriptが完全に有効な活字体である":「それはありますランタイムエラー"。

エラーが発生した理由を回答してみましょう。あなたはHomePageクラス外ga変数を置くので、あなたのHomePage方法(ionViewDidLoad())で、あなたはga変数がthis.gaを使用してHomePageのプロパティであるかのようにga変数にアクセスしようとした一方で

エラーが発生します。したがって、そのエラーが発生します。 JavaScriptは完全に有効な活字体である -

export class HomePage() { 
    // .... 

    ga = { 
     // .... 
    }; 

    ionViewDidLoad(){ 
     // `this.ga` is called here, now `this.ga` shouldn't throw the error 
    } 
} 
+0

それは私に以前と同じエラーを与えている –

関連する問題