Monday 25 March 2019

org.bson.codecs.configuration.CodecConfigurationException: Unable to get value for property

Problem : 

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.time.LocalDate.

org.bson.codecs.configuration.CodecConfigurationException: Unable to get value for property


Solution :

Try creating your bean by this way to help POJO classes.


 @Bean
    public MongoDatabase mongoDatabase() {
        try {
            CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
                    fromProviders(PojoCodecProvider.builder().automatic(true).build()));
     
            String connectionString = "mongodb+srv://" + username + ":" + password + "@" + host + "/" + database + "";
            log.info("Connection String " + connectionString);
            MongoClientURI uri = new MongoClientURI(connectionString);
            MongoClient mongoClient = new MongoClient(uri);

            MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
            return database;
        } catch (Exception e) {
            log.error("Error in Connection " + e);
            return null;
        }
    }



org.mongodb.driver.connection : Closed connection [connectionId] because there was a socket exception raised by this connection.

Problem : 

org.mongodb.driver.connection : Closed connection [connectionId{localValue:22}] because there was a socket exception raised by this connection.


Solution:

1. Check your username password combination
2. VPC Settings if you are on Company network
3. Check firefall in not blocking the PORT 27017
4. Make sure user you have created have given required rights.
5. Your Ip address should exists in the list of whitelist IP's in the setting tab of Atlas.



Friday 22 March 2019

Can't bind to 'formGroup' since it isn't a known property of 'form'

ERROR:

Can't bind to 'formGroup' since it isn't a known property of 'form'


Solution :

To fix this error, you just need to import ReactiveFormsModule from @angular/forms in your module.

Here's the example of a basic module with ReactiveFormsModule import:



import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

Wednesday 13 March 2019

Show vehicle moving in google map angular 6


In this tutorial we will learn about how to show your vehicle moving on map.

Below are the prerequisite 


If you followed above two tutorials you have added waypoints and also set direction in the map.

Now we just need to set our vehicle live location.

make changes in your app.component.ts or any file in which you have made your map changes.


app.component.ts

import { Component } from '@angular/core';
import { interval } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
})
export class AppComponent {
  title = 'Google Map';
  lat = 51.678418;
  lng = 7.809007;
  public origin: { lat: 51.673858, lng: 7.815982 };
  public destination: { lat: 51.723858, lng: 7.895982 };
  timerSubscription: any;
  currentLat: any;
  currentLng: any;
  
  icon = {
    url: ('../../assets/icons/bus.svg'),
    scaledSize: {
      height: 60,
      width: 60
    }
  };
  waypoints = [
    {
      location: { lat: 51.673858, lng: 7.815982 },
      stopover: true
    },
    {
      location: { lat: 51.373858, lng: 7.215982 },
      stopover: true
    },
    {
      location: { lat: 51.723858, lng: 7.895982 },
      stopover: true
    }
  ];

  constructor(private httpClient: HttpClient) {

    //Timer to fetch data on an interval

    this.timerSubscription = interval(1000)
      .subscribe(() => this.getCurrentLocationOfVehicle());
  }

  getCurrentLocationOfVehicle() {

    const requestMap: any = {};
    requestMap.userName = 'userName';
    requestMap.password = 'password';
    // replace it with your feed URL 
    requestMap.gpsTrackUrl = 'http://tracking/url/';

    this.getCurrentLatLong(requestMap).subscribe(data => {
      //set current lat lng of vehicle
      this.currentLat = data.lat;
      this.currentLng = data.long;
    },
      err => console.log('error in fetching data' + err),
      () => console.log('done')
    );
  }
  getCurrentLatLong(trackData): any {
    return this.httpClient.post('trackUrl', trackData);
  }

}


make changes in your app.component.html or any file in which you have made your map changes.

app.component.html 
<agm-map [latitude]="lat" [longitude]="lng">

<agm-direction 
  [origin]="origin" 
  [destination]="destination"
  [waypoints]="waypoints"
  [travelMode]="'DRIVING'">
</agm-direction>
   
<!-- Show live location of vehicle -->
<agm-marker 
  [latitude]="currentLat" 
  [longitude]="currentLng" 
  [iconUrl]="icon">
</agm-marker>
</agm-map>



This will show your vehicle moving in the desired direction.


let me know in comments if you face any issue.





Tuesday 12 March 2019

Get adddress using lat lng in angular 6

If you are using agm-map then its quite easy to fetch address using lattitude and longitude.

Below function will work to get city name from lat lng.

 public latLngToCityName(latitude, longitude) {
    let _this = this;
    const cityDetails = { city: '', lat: latitude, lng: longitude };
    this.geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);
    this.geocoder.geocode({ 'latLng': latlng }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          //formatted address
          for (var i = 0; i < results[0].address_components.length; i++) {
            for (var b = 0; b < results[0].address_components[i].types.length; b++) {
              //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
              if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                //this is the object you are looking for
                let city = results[0].address_components[i];
                cityDetails.city = city.long_name;
                _this.cityDetails = cityDetails;
              }
            }
          }
        } else {
          cityDetails.city = '';
        }
      } else {
        cityDetails.city = '';
        console.log('Failed');
      }
    });
  }



if you are getting error like google not defined or its not able to find google map then install below dependency.

npm i @types/googlemaps




Directions and Waypoints in google map using AGM map angular 6




If you have not Setup agm map till now then check this post Google map in angular 6 



First Install NPM direction module in your project.


npm i @agm/core
npm i agm-direction



Import direction module in app.component.ts :

Importing Modules
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
 
import { AgmCoreModule } from '@agm/core';            // @agm/core
import { AgmDirectionModule } from 'agm-direction';   // agm-direction
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgmCoreModule.forRoot({ // @agm/core
      apiKey: 'your key',
    }),
    AgmDirectionModule,     // agm-direction
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Open the file src/app/app.component.ts and paste the following content:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
})
export class AppComponent {
  title: string = 'Google Map';
  lat: number = 51.678418;
  lng: number = 7.809007;
  public origin: { lat: 51.673858, lng: 7.815982 };
  public destination: { lat: 51.723858, lng: 7.895982 };
  waypoints = [
    {
      location: { lat: 51.673858, lng: 7.815982 },
      stopover: true
    },
    {
      location: { lat: 51.373858, lng: 7.215982 },
      stopover: true
    },
    {
      location: { lat: 51.723858, lng: 7.895982 },
      stopover: true
    }
  ]
}


Open the file src/app/app.component.html and paste the following content:

app.component.html :

<agm-map [latitude]="lat" [longitude]="lng">
  <agm-direction [origin]="origin" [destination]="destination" 
  [waypoints]="waypoints" [travelMode]="'DRIVING'">
</agm-direction>
</agm-map>


This will create direction and also add your waypoints in the direction.



Multiple markers on google map angular 6


If you have not Setup agm map till now then check this post  Google map in angular 6 .

we’ll now use already created MAP to load our markers. Open the file src/app/app.component.ts and modify it like below:


app.component.ts :
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
})
export class AppComponent {
    title: string = 'Google Map';
    lat: number = 51.678418;
    lng: number = 7.809007;

    markers = [
        {
            lat: 51.673858,
            lng: 7.815982,
            label: 'A'
        },
        {
            lat: 51.373858,
            lng: 7.215982,
            label: 'B'
        },
        {
            lat: 51.723858,
            lng: 7.895982,
            label: 'C'
        }
    ]
}


Open the file src/app/app.component.html and paste the following content:

Preview:
<agm-map [latitude]="lat" [longitude]="lng">
<agm-marker  *ngFor="let marker of markers" [latitude]="marker.lat" 
  [longitude]="marker.lng">
</agm-map>

this will create multiple markers on the map.



Google Map in Angular 6

Getting Started


We start by creating a project with Angular CLI. Angular CLI makes it easy to create an application that already works and allows you to follow the best practices. I you haven’t installed Angular CLI yet, please run the following command first:


npm install -g @angular/cli



ng new agm-project


cd agm-project


Setting up Angular Google Maps


First and foremost, in order to do any kind of interaction with the Maps API, you need an API key from Google. Follow the instructions  Google Map API key


Install and configure Angular Google Maps


From your project folder, run the following command:

npm i @agm/core --save

Add agmcore module entry in  app.module.ts


 app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_KEY'
    })
  ],
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}



Angular CLI already created an app component the we’ll now use to create our first google map. Open the file src/app/app.component.ts and modify it like below:


app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
})
export class AppComponent {
  title: string = 'Google Map';
  lat: number = 51.678418;
  lng: number = 7.809007;
}


Setup the template

Open the file src/app/app.component.html and paste the following content:


app.component.html 

<h1>{{ title }}</h1>

<agm-map [latitude]="lat" [longitude]="lng">
  <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>


Now in your templates you can include the map component.

Note: you must explicitly set the height of the agm-map element in CSS otherwise it will not show up on screen.

Setup the CSS file

Open the file src/app/app.component.css and paste the following content:

app.component.css


agm-map {
  height: 300px;
}


   
And there you have it! It really is that simple to get it set up. However, there are a host of other options and components that you can use to enrich the Google Maps experience.

Let me know in comments for any issue you are facing.

Spring boot with CORS

CORS (Cross-Origin Resource Sharing) errors occur when a web application running in a browser requests a resource from a different domain or...