DeepLearning4J: Shapes do not match on FeedForward Auto Encoder - deep-learning

I'm implementing an auto-encoder for anomaly detection of IoT sensor data. My data set comes from a simulation, but basically it is accelerometer data - three dimensions, one for each axis.
I'm reading it from a CSV file, column 2-4 contain the data - sorry for the code quality, it is quick and dirty:
private static DataSetIterator getTrainingData(int batchSize, Random rand) {
double[] ix = new double[nSamples];
double[] iy = new double[nSamples];
double[] iz = new double[nSamples];
double[] ox = new double[nSamples];
double[] oy = new double[nSamples];
double[] oz = new double[nSamples];
Reader in;
try {
in = new FileReader("/Users/romeokienzler/Downloads/lorenz_healthy.csv");
Iterable<CSVRecord> records;
records = CSVFormat.DEFAULT.parse(in);
int index = 0;
for (CSVRecord record : records) {
String[] recordArray = record.get(0).split(";");
ix[index] = Double.parseDouble(recordArray[1]);
iy[index] = Double.parseDouble(recordArray[2]);
iz[index] = Double.parseDouble(recordArray[3]);
ox[index] = Double.parseDouble(recordArray[1]);
oy[index] = Double.parseDouble(recordArray[2]);
oz[index] = Double.parseDouble(recordArray[3]);
index++;
}
INDArray ixNd = Nd4j.create(ix);
INDArray iyNd = Nd4j.create(iy);
INDArray izNd = Nd4j.create(iz);
INDArray oxNd = Nd4j.create(ox);
INDArray oyNd = Nd4j.create(oy);
INDArray ozNd = Nd4j.create(oz);
INDArray iNd = Nd4j.hstack(ixNd, iyNd, izNd);
INDArray oNd = Nd4j.hstack(oxNd, oyNd, ozNd);
DataSet dataSet = new DataSet(iNd, oNd);
List<DataSet> listDs = dataSet.asList();
Collections.shuffle(listDs, rng);
return new ListDataSetIterator(listDs, batchSize);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
return null;
}
}
This is the net:
public static void main(String[] args) {
// Generate the training data
DataSetIterator iterator = getTrainingData(batchSize, rng);
// Create the network
int numInput = 3;
int numOutputs = 3;
int nHidden = 1;
int listenerFreq = batchSize / 5;
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(seed)
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(1.0).iterations(iterations).momentum(0.5)
.momentumAfter(Collections.singletonMap(3, 0.9))
.optimizationAlgo(OptimizationAlgorithm.CONJUGATE_GRADIENT).list(2)
.layer(0,
new AutoEncoder.Builder().nIn(numInput).nOut(nHidden).weightInit(WeightInit.XAVIER)
.lossFunction(LossFunction.RMSE_XENT).corruptionLevel(0.3).build())
.layer(1, new OutputLayer.Builder(LossFunction.NEGATIVELOGLIKELIHOOD).activation("softmax").nIn(nHidden)
.nOut(numOutputs).build())
.pretrain(true).backprop(false).build();
MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();
model.setListeners(Collections.singletonList((IterationListener) new ScoreIterationListener(listenerFreq)));
for (int i = 0; i < nEpochs; i++) {
iterator.reset();
model.fit(iterator);
}
}
I'm getting the following error:
Shapes do not match: x.shape=[1, 9000], y.shape=[1, 3]
Exception in thread "main" java.lang.IllegalArgumentException: Shapes do not match: x.shape=[1, 9000], y.shape=[1, 3]
at org.nd4j.linalg.api.parallel.tasks.cpu.CPUTaskFactory.getTransformAction(CPUTaskFactory.java:92)
at org.nd4j.linalg.api.ops.executioner.DefaultOpExecutioner.doTransformOp(DefaultOpExecutioner.java:409)
at org.nd4j.linalg.api.ops.executioner.DefaultOpExecutioner.exec(DefaultOpExecutioner.java:62)
at org.nd4j.linalg.api.ndarray.BaseNDArray.subi(BaseNDArray.java:2660)
at org.nd4j.linalg.api.ndarray.BaseNDArray.subi(BaseNDArray.java:2641)
at org.nd4j.linalg.api.ndarray.BaseNDArray.sub(BaseNDArray.java:2419)
at org.deeplearning4j.nn.layers.feedforward.autoencoder.AutoEncoder.computeGradientAndScore(AutoEncoder.java:123)
at org.deeplearning4j.optimize.solvers.BaseOptimizer.gradientAndScore(BaseOptimizer.java:132)
at org.deeplearning4j.optimize.solvers.BaseOptimizer.optimize(BaseOptimizer.java:151)
at org.deeplearning4j.optimize.Solver.optimize(Solver.java:52)
at org.deeplearning4j.nn.layers.BaseLayer.fit(BaseLayer.java:486)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.pretrain(MultiLayerNetwork.java:170)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.fit(MultiLayerNetwork.java:1134)
at org.deeplearning4j
.examples.feedforward.autoencoder.AnomalyDetector.main(AnomalyDetector.java:136)
But I'm not defining dimension anywhere and IMHO the dimensions of input and output should be (3,3000) and (3,3000). Where is my mistake?
Thanks a lot in advance...
EDIT: UPDATE to latest release 13.9.16
I'm getting the same error (semantically), here is what I'm doing now:
private static DataSetIterator getTrainingData(int batchSize, Random rand) {
double[] ix = new double[nSamples];
double[] iy = new double[nSamples];
double[] iz = new double[nSamples];
double[] ox = new double[nSamples];
double[] oy = new double[nSamples];
double[] oz = new double[nSamples];
try {
RandomAccessFile in = new RandomAccessFile(new File("/Users/romeokienzler/Downloads/lorenz_healthy.csv"),
"r");
int index = 0;
String record;
while ((record = in.readLine()) != null) {
String[] recordArray = record.split(";");
ix[index] = Double.parseDouble(recordArray[1]);
iy[index] = Double.parseDouble(recordArray[2]);
iz[index] = Double.parseDouble(recordArray[3]);
ox[index] = Double.parseDouble(recordArray[1]);
oy[index] = Double.parseDouble(recordArray[2]);
oz[index] = Double.parseDouble(recordArray[3]);
index++;
}
INDArray ixNd = Nd4j.create(ix);
INDArray iyNd = Nd4j.create(iy);
INDArray izNd = Nd4j.create(iz);
INDArray oxNd = Nd4j.create(ox);
INDArray oyNd = Nd4j.create(oy);
INDArray ozNd = Nd4j.create(oz);
INDArray iNd = Nd4j.hstack(ixNd, iyNd, izNd);
INDArray oNd = Nd4j.hstack(oxNd, oyNd, ozNd);
DataSet dataSet = new DataSet(iNd, oNd);
List<DataSet> listDs = dataSet.asList();
Collections.shuffle(listDs, rng);
return new ListDataSetIterator(listDs, batchSize);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
return null;
}
}
And here the net:
// Set up network. 784 in/out (as MNIST images are 28x28).
// 784 -> 250 -> 10 -> 250 -> 784
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).iterations(1)
.weightInit(WeightInit.XAVIER).updater(Updater.ADAGRAD).activation("relu")
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT).learningRate(learningRate)
.regularization(true).l2(0.0001).list().layer(0, new DenseLayer.Builder().nIn(3).nOut(1).build())
.layer(1, new OutputLayer.Builder().nIn(1).nOut(3).lossFunction(LossFunctions.LossFunction.MSE).build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.setListeners(Collections.singletonList((IterationListener) new ScoreIterationListener(1)));
// Load data and split into training and testing sets. 40000 train,
// 10000 test
DataSetIterator iter = getTrainingData(batchSize, rng);
// Train model:
int nEpochs = 30;
while (iter.hasNext()) {
DataSet ds = iter.next();
for (int epoch = 0; epoch < nEpochs; epoch++) {
net.fit(ds.getFeatures(), ds.getLabels());
System.out.println("Epoch " + epoch + " complete");
}
}
My error is:
Exception in thread "main" java.lang.IllegalStateException: Mis matched lengths: [9000] != [3]
at org.nd4j.linalg.util.LinAlgExceptions.assertSameLength(LinAlgExceptions.java:39)
at org.nd4j.linalg.api.ndarray.BaseNDArray.subi(BaseNDArray.java:2786)
at org.nd4j.linalg.api.ndarray.BaseNDArray.subi(BaseNDArray.java:2767)
at org.nd4j.linalg.api.ndarray.BaseNDArray.sub(BaseNDArray.java:2547)
at org.deeplearning4j.nn.layers.BaseOutputLayer.getGradientsAndDelta(BaseOutputLayer.java:182)
at org.deeplearning4j.nn.layers.BaseOutputLayer.backpropGradient(BaseOutputLayer.java:161)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.calcBackpropGradients(MultiLayerNetwork.java:1125)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.backprop(MultiLayerNetwork.java:1077)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.computeGradientAndScore(MultiLayerNetwork.java:1817)
at org.deeplearning4j.optimize.solvers.BaseOptimizer.gradientAndScore(BaseOptimizer.java:152)
at org.deeplearning4j.optimize.solvers.StochasticGradientDescent.optimize(StochasticGradientDescent.java:54)
at org.deeplearning4j.optimize.Solver.optimize(Solver.java:51)
at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.fit(MultiLayerNetwork.java:1445)
at org.deeplearning4j.examples.feedforward.anomalydetection.IoTAnomalyExample.main(IoTAnomalyExample.java:110)
I'm pretty sure I'm messing up with the training data - the shape of the training data is 3000 rows, 3 columns - same for the target (the very same data because I want to build an autoencoder) - test data can be found here:
https://pmqsimulator-romeokienzler-2310.mybluemix.net/data
Any ideas?

Thanks to Alex Black of Skymind, this is the solution (got the shape wrong)
INDArray ixNd = Nd4j.create(ix, new int[]{3000,1});
INDArray iyNd = Nd4j.create(iy, new int[]{3000,1});
INDArray izNd = Nd4j.create(iz, new int[]{3000,1});
INDArray oxNd = Nd4j.create(ox, new int[]{3000,1});
INDArray oyNd = Nd4j.create(oy, new int[]{3000,1});
INDArray ozNd = Nd4j.create(oz, new int[]{3000,1});

Related

Code error using MNIST example of deeplearning4j

Help me please! I'm working on a project using deeplearning4j. The MNIST example works very well but I get an error with my dataset.
My data set has two outputs.
int height = 45;
int width = 800;
int channels = 1;
int rngseed = 123;
Random randNumGen = new Random(rngseed);
int batchSize = 128;
int outputNum = 2;
int numEpochs = 15;
File trainData = new File("C:/Users/JHP/Desktop/learningData/training");
File testData = new File("C:/Users/JHP/Desktop/learningData/testing");
FileSplit train = new FileSplit(trainData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
FileSplit test = new FileSplit(testData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
ParentPathLabelGenerator labelMaker = new ParentPathLabelGenerator();
ImageRecordReader recordReader = new ImageRecordReader(height, width, channels, labelMaker);
ImageRecordReader recordReader2 = new ImageRecordReader(height, width, channels, labelMaker);
recordReader.initialize(train);
recordReader2.initialize(test);
DataSetIterator dataIter = new RecordReaderDataSetIterator(recordReader, batchSize, 1, outputNum);
DataSetIterator testIter = new RecordReaderDataSetIterator(recordReader2, batchSize, 1, outputNum);
DataNormalization scaler = new ImagePreProcessingScaler(0, 1);
scaler.fit(dataIter);
dataIter.setPreProcessor(scaler);
System.out.println("Build model....");
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(rngseed)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.iterations(1)
.learningRate(0.006)
.updater(Updater.NESTEROVS).momentum(0.9)
.regularization(true).l2(1e-4)
.list()
.layer(0, new DenseLayer.Builder()
.nIn(height * width)
.nOut(1000)
.activation(Activation.RELU)
.weightInit(WeightInit.XAVIER)
.build()
)
.layer(1, newOutputLayer.Builder(LossFunction.NEGATIVELOGLIKELIHOOD)
.nIn(1000)
.nOut(outputNum)
.activation(Activation.SOFTMAX)
.weightInit(WeightInit.XAVIER)
.build()
)
.pretrain(false).backprop(true)
.build();
MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();
model.setListeners(new ScoreIterationListener(1));
System.out.println("Train model....");
for (int i = 0; i < numEpochs; i++) {
try {
model.fit(dataIter);
} catch (Exception e) {
System.out.println(e);
}
}
error is
org.deeplearning4j.exception.DL4JInvalidInputException: Input that is
not a matrix; expected matrix (rank 2), got rank 4 array with shape
[128, 1, 45, 800]
You're initializing the neural net wrong. If you look closer at every cnn example in the dl4j examples repo (hint: this is the canonical source of where you should be pulling code from, anything else will likely be invalid or out of date: https://github.com/deeplearning4j/dl4j-examples)
You'll notice in all of our examples we have an inputType config:
https://github.com/deeplearning4j/dl4j-examples/blob/master/dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/LenetMnistExample.java#L114
There are various types you should be using you should never set nIn manually. Just nOut.
For mnist, we use convolutional flat and convert it in to a 4d dataset automaticall for you.
Mnist starts off as a flat vector, but a cnn only understands 3d data. We do that transition and reshape for you.

Implicit coercion of a value of type Number to an unrelated type flash.display:MovieClip

When I try to pass a MovieClip through a function I get the error:
"Implicit coercion of a value of type Number to an unrelated type flash.display:MovieClip"
Room generation class:
public var generatedRoom:Array;
public function enemyPack():void
{
//trace(generatedRoom[createdRooms]);
var random:int = Main.getRandom(0,5);
switch(random)
{
case 0:
Main.spawnEnemy(roomX+Main.getRandom(50, room.width-50),generatedRoom[createdRooms],roomY+Main.getRandom(50, room.height-50));
break;
}
}
Enemy class:
public function spawn(setX:int,setY:int, inRoom:MovieClip ,b:int = 0):void
{
timeToSlow = Main.getRandom(500,1500)
type = b;
isDestroyed = false;
switch(type)
{
case 0:
life = 100 + (Math.pow(Main.dific,4));
maxLife = life;
model = new MC_EnemigoD();
bulletSpeed = Main.getRandom(3,6);
timeToMove = 400;
bulletModel = new MC_BulletE();
speed = 1 + (Main.nivel)/2;
aggro = 250;
break;
case 1:
life = 125 + (Math.pow(Main.dific,4));
maxLife = life;
model = new MC_EnemigoC();
speed = 0.5 /*+ (Main.nivel)/2*/;
break;
case 2:
life = 500 + (Math.pow(Main.dific,4));
maxLife = life;
model = new MC_BossM();
speed = 1 + (Main.nivel)/2;
timeToMove = Main.getRandom(400,600);
bulletModel = new MC_BulletC();
bulletSpeed = Main.getRandom(6,9);
timeToShoot = Main.getRandom(1500,2000);
aggro = 400;
break;
case 3:
life = 400 + (Math.pow(Main.dific,4));
maxLife = life;
model = new MC_Troll();
speed = 0.6 /* + (Main.nivel)/2*/;
break;
case 4:
life = 1000 + (Math.pow(Main.dific,4));
maxLife = life;
model = new MC_BossB();
model.scaleX = 0.5;
model.scaleY = 0.5;
speed = 3 + (Main.nivel)/2;
break;
}
model.addChild(shadow);
//Main.render.
Main.render.addChild(model);
model.gotoAndPlay("spawn")
model.y = setY;
model.x = setX;
realHeight = model.height;
realWidth = model.width;
shadow.scaleX = model.scaleX + 0.1;
shadow.scaleY = model.scaleY;
shadow.x = (model.hitBox.width/2)+6-(shadow.width/2);
shadow.y = (model.hitBox.height)-9;
model.setChildIndex(shadow, 0);
model.addChild(hpBar);
hpBar.addChild(hpBarColor);
hpBarColor.scaleY = 0.9;
hpBarColor.scaleX = 0.97;
hpBarColor.y = 1;
hpBarColor.x = 1;
hpBar.scaleY = 0.7;
hpBar.x = (model.hitBox.width/2)+5-(hpBar.width/2);
hpBar.y = (model.hitBox.height)+(hpBar.height);
model.hitBox.visible = false;
}
Main class:
public static function spawnEnemy(setX:int,setY:int, inRoom:MovieClip, t:int = 0):void
{
//trace(setX,setY)
var temp:Enemy = new Enemy();
temp.spawn(setX,setY, inRoom, t);
allEnemies.push(temp);
}
and when I trace the variable it returns [object MC_"myMovieClip"]
If I guessed with the line causing your error
looks like your spawnEnemy call
Main.spawnEnemy(roomX+Main.getRandom(50, room.width-50),//int
generatedRoom[createdRooms],//a MovieClip?
roomY+Main.getRandom(50, room.height-50)//int
);//(int, MovieClip(?), int)
doesn`t have the right order of arguments:
spawnEnemy(setX:int,
setY:int,
inRoom:MovieClip,
t:int = 0)//(int, int, MovieClip)

How to add MultiPolygon do Android Google Maps v2 from WKT

I have geometries in a spatialite database. With the help of jts topology suite I managed to draw some simple polygons on google maps v2, transforming WKT in a coordinate array. But I can't figure out how to draw multipolygons correctly. The individual smaller shapes are connected and they shouldn't be.
Correct Polygon:
Faulty MultiPolygon:
How it should be:
So after a few days trying I got it working like this.
I hope it helps someone.
private void test(){
GeometryFactory geometryFactory = new GeometryFactory();
WKTReader reader=new WKTReader(geometryFactory);
PolygonOptions polyOptions = null;
ArrayList<String> featureList = new ArrayList<String>();
MultiPolygon multipolygon = null;
Polygon polygon = null;
Coordinate[] outerCoordinates = null;
Coordinate[] innerCoordinates = null;
ArrayList<LatLng> outer = null;
ArrayList<LatLng> inner = null;
try {
//Gets a list of features in WKT format
featureList = HtmlActivity.mDbHelper.getFeatureList();
//Iterates the feature list
for (String feature : featureList) {
multipolygon = (MultiPolygon) reader.read(feature);
//Gets each polygon of a multipolygon
for(int i = 0; i < multipolygon.getNumGeometries(); i++)
{
outer = new ArrayList<LatLng>();
polyOptions = new PolygonOptions();
polygon = (Polygon) multipolygon.getGeometryN(i);
//Gets each polygon outer coordinates
outerCoordinates = polygon.getExteriorRing().getCoordinates();
for (Coordinate outerCoordinate : outerCoordinates){
outer.add(new LatLng(outerCoordinate.y, outerCoordinate.x));
}
polyOptions.addAll(outer);
//Getting each polygon interior coordinates (hole) if they exist
if(polygon.getNumInteriorRing() > 0){
for(int j = 0; j < polygon.getNumInteriorRing(); j++){
inner = new ArrayList<LatLng>();
innerCoordinates = polygon.getInteriorRingN(j).getCoordinates();
for (Coordinate innerCoordinate : innerCoordinates){
inner.add(new LatLng(innerCoordinate.y, innerCoordinate.x));
}
polyOptions.addHole(inner);
}
}
polyOptions.strokeColor(Color.rgb(30, 30, 30));
polyOptions.strokeWidth(2);
polyOptions.fillColor(Color.argb(255, 255, 0, 0));
googleMap.addPolygon(polyOptions);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Flex Mobile actionscript how to alphabetically sort a arrayCollection by a portion of a object

I've got a query from a db that is returned as a ArrayCollection of Objects. I want to alphabetically sort by one property of the object. Coming back from the db.queryResults() the name of the property of the object is DmvValue3. How to I sort this. Below is my code and a screenshot of the Property from the ArrayCollection.
private function sortCollection(list:ArrayCollection):ArrayCollection
{
var sort:ISort = new Sort();
var sortField:SortField = new SortField(null, true);
sortField.setStyle("locale", "en-US");
sort.fields = [sortField];
list.sort = sort;
list.refresh();
return list;
}
This is untested code, but it should get you on the correct path.
private function sortCollection(list:ArrayCollection):ArrayCollection {
var sort:ISort = new Sort();
var sortField:SortField = new SortField();
sortField.name = "DmvValue3";
sortField.caseInsensitive = true;
sortField.numeric = true;
sortField.descending = true;
sort.fields = [sortField];
list.sort = sort;
list.refresh();
return list;
}
[UPDATE]
private function sortCollection(list:ArrayCollection):ArrayCollection {
var sort:ISort = new Sort();
var sortField:SortField = new SortField();
//sortField.name = "DmvValue3";
//sortField.caseInsensitive = true;
////sortField.numeric = true;
//sortField.descending = true;
//sort.fields = [sortField];
sort.compareFunction = myCompare;
list.sort = sort;
list.refresh();
return list;
}
public function myCompare(a:Object, b:Object, fields:Array = null):int {
if(a["DmvValue3"] < b["DmvValue3"] )
return -1; // -1, if a should appear before b in the sorted sequence
if(a["DmvValue3"] == b["DmvValue3"] )
return 0; // 0, if a equals b
if(a["DmvValue3"] > b["DmvValue3"] )
return 1; // 1, if a should appear after b in the sorted sequence
}

Map Route with WCF Services

I have use WCF Services in an app.
I draw the line when going from 1 lists the coordinates returned from WCF. Then draw the wrong path. While Windows Phone 7 displays properly, using Polyline.
Shown below are the results that I got wrong:
And I want to display:
This is the code that I handle to draw:
void wcl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (string.IsNullOrEmpty(e.Result) || e.Error != null)
{
MessageBox.Show("Lỗi kết nối! Hãy thử lại");
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
return;
}
XuLyToaDo route = XuLyToaDo.TaoMapRoute();
//Lay ds diem ve
string Ketqua = XuLyToaDo.DanhSachDiemVe(e.Result);
string[] kq = Ketqua.Split('&');
//Lay thong tin toa do
XuLyToaDo routePushpin = XuLyToaDo.TaoMapRoute();
XuLyToaDo routePolyline = XuLyToaDo.TaoMapRoute();
//MessageBox.Show(kq[0]);
//MessageBox.Show(kq[1]);
//MessageBox.Show(kq[2]);
//Tao ds toa do
List<GeoCoordinate> lsToaDoPushpin = routePushpin.TaoDSToaDo(kq[0]);
List<GeoCoordinate> lsToaDoRoute = routePushpin.TaoDSToaDo(kq[1]);
// Lay ds ten duong
string[] MangTenDiaChi = routePushpin.TaoDSDuong(kq[2]);
if (lsToaDoPushpin == null)
{
MessageBox.Show("Không có thông tin");
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
return;
}
for (int i = 0; i < lsToaDoPushpin.Count - 1; i++)
{
AddRoute(lsToaDoPushpin[i], Colors.Blue);
}
//ve duong di
for (int i = 0; i < lsToaDoPushpin.Count - 2; i++)
{
AddRouteMap(lsToaDoPushpin[i], lsToaDoPushpin[i + 1]);
}
//ve duong di
//MyRouteQuery = new RouteQuery()
//{
// TravelMode = TravelMode.Driving,
// Waypoints = lsToaDoRoute
//};
//MyRouteQuery.QueryCompleted += MyRouteQuery_QueryCompleted;
//MyRouteQuery.QueryAsync();
//Them danh sach tram
int k = 0;
foreach (GeoCoordinate geo in lsToaDoPushpin)
{
if (k == lsToaDoPushpin.Count() - 1)
break;
Pushpin pus = new Pushpin();
string str = "Direc_" + k;
pus.Template = Maps.App.Current.Resources[str] as ControlTemplate;
pus.Tag = k;
pus.Content = k.ToString() + ". " + MangTenDiaChi[k];
pus.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(pus_Tap);
MyMap.Layers.Add(new MapLayer()
{
new MapOverlay()
{
GeoCoordinate = geo,
PositionOrigin = new Point(0.5,0.5),
Content = pus
}
});
k++;
}
MyMap.Center = lsToaDoPushpin[0];
MyMap.ZoomLevel = 15;
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
}
catch (Exception ex)
{
MessageBox.Show("Lỗi kết nối. Hãy thử lại!!" + ex.Message);
}
}
private void AddRouteMap(GeoCoordinate g1, GeoCoordinate g2)
{
List<GeoCoordinate> lsRoute = new List<GeoCoordinate>();
lsRoute.Add(g1);
lsRoute.Add(g2);
MyRouteQuery = new RouteQuery()
{
TravelMode = TravelMode.Walking,
Waypoints = lsRoute
};
MyRouteQuery.QueryCompleted += MyRouteQuery_QueryCompleted;
MyRouteQuery.QueryAsync();
}
void MyRouteQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
if (e.Error == null)
{
if (MyMapRoute != null)
AddlstMapRoute(MyMapRoute);
MyRoute = e.Result;
MyMapRoute = new MapRoute(MyRoute);
MyMap.AddRoute(MyMapRoute);
}
}
private void AddlstMapRoute(MapRoute maproute)
{
lsMapRoute.Add(maproute);
}
private void AddRoute(GeoCoordinate geo, Color color)
{
MyMap.Layers.Add(new MapLayer()
{
new MapOverlay()
{
GeoCoordinate = geo,
PositionOrigin = new Point(0.5,0.5),
Content = new Ellipse
{
Fill = new SolidColorBrush(color),
Width =5,
Height = 5
}
}
});
}
void pus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
e.Handled = true;
Pushpin pus = sender as Pushpin;
ToolTipService.SetToolTip(pus, new ToolTip()
{
DataContext = pus,
Style = Application.Current.Resources["CustomInfoboxStyle"] as Style
});
MessageBox.Show(pus.Content.ToString(), "Thông tin trạm", MessageBoxButton.OK);
}
This is the place where I create database:
How can I fix this?
i guess its due to the fact that your travelmode is set to walking and google seems to think that walking there isnt allowed, so it takes the next possible way. try change the travelmode to driving or so.
greetings lars