02 July, 2019

Find the nearest place by using postcode or zipcode.

In the previous post we had seen how to get the current location (latitude and longitude) using java script.  Today we will use that functionality to get the nearby search using Google API.  We usually  do the search the near by restaurants , ATM, airport, book store , medicine store ,etc.  By the way we need this everyday in our daily life. 

We sometimes search the specific place or location by using the zipcode or pincode. Google API provide many features for Places, Routes and Map. Today we will find the nearest "resturants" by using a zip code or postcode. 

We have used google.maps.places and google.maps.geocoder in our example above. We have used geocoder , it is the process of converting addresses (like a street address) into geographic coordinates (like latitude and longitude), which you can use to place markers on a map, or position the map.


zipcodefind.html

<html>
<head>
        <style>
            html,
            body,
            #map-canvas {
                height: 100%;
                margin: 0px;
                padding: 0px
            }
        </style>
    <script
        src="https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY"></script>
   
   
   
    <script language="javascript">
        var map;
        var infowindow;
        function initialize() {
            var geocoder = new google.maps.Geocoder();
            var zipcode = document.getElementById('zipcode').value;
            geocoder.geocode({
                'address': zipcode, componentRestrictions: { country: 'IN' }
            }, function (results, status) {
                if (status === 'OK') {
                    var latLong = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                    console.log("Co-ordinates are::" + latLong);
                    map = new google.maps.Map(document.getElementById('map-canvas'), {
                        center: latLong,
                        zoom: 15
                    });
                    var request = {
                        location: latLong,
                        radius: 1000,
                        types: ['car_repair']
                    };
                    infowindow = new google.maps.InfoWindow();
                    var service = new google.maps.places.PlacesService(map);
                    service.nearbySearch(request, callback);
                } else {
                    alert('Search was not successful for the following reason: ' + status);
                }
            });
        }
        function callback(results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                for (var i = 0; i < results.length; i++) {
                    createMarker(results[i]);
                }
            }
        }
        function createMarker(place) {
            var placeLoc = place.geometry.location;
            var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location
            });
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent(place.name);
                infowindow.open(map, this);
            });
        }       
    </script>
</head>
<body>
    <div id="map-canvas" style="width: 50%; float:right"></div>
    <div style="width: 50%; float:left;padding-top: 20px;">
        <input id="zipcode" type="textbox" value="560078">
        <input id="submit" type="button" value="Get Nearby Search by Postcode" onclick="initialize()">
        <br>
        <span style="font-size: small">In this example we have used country <b>India</b>, and search type is <b>Resturants</b> </span>
    </div>
</body>
</html>




Now we will open this html file on browser as below screenshot. We have used marker for marking the near by place "resturants" for the given postcode. There are many supported place type google provides.
















In this example we have restricted the search inside India. But there are other country codes i.e. AU which is also supported. 

componentRestrictions: { country: 'IN' }


Find few reference documents below:-




Happy Learning. 

01 July, 2019

Top 5 interview questions on BlockingQueue


1) What is BlockingQueue ? Under which package of JDK its available ?

Ans- A blocking queue is an interface. BlockingQueue implementations are thread-safe. It helps to handle multi threaded execution , specially its for producer and consumer problem.
The queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. 

A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. 

There are few implementation for this BlockingQueue as below, all these classes available under java.util.concurrent package.
  • ArrayBlockingQueue
  • SyncronousBlockingQueue
  • PriorityBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue


2) What is the use of these methods peek(), poll(), take() and remove() ?

Ans - 
peek() :- This retrieves, but does not remove, the head of this queue,or returns null if this queue is empty. It doesn't throw any exception.

poll() :- This retrieves and removes the head of this queue,or returns null if this queue is empty.It doesn't throw any exception.

take() :- This retrieves and removes the head of this queue, waiting if necessary until an element becomes available. This method waits for certain time , if its interrupted then it throws InterruptedException. 

remove() :- This retrieves and removes the head of this queue. This method differs from poll() only in that it throws an exception (NoSuchElementException ) if this queue is empty.

Apart from the above difference take() method is provided by BlockingQueue i.e. java.util.concurrent.BlockingQueue.take(). Where as other methods provided by Queue i.e.  java.util.Queue.poll(), java.util.Queue.peek(), java.util.Queue.remove()


3) Is this possible to declare BlockingQueue implementation with ZERO/0 size?

Ans- Yes, if its unbounded implementation. But,if its bounded then we have to provide a capacity. The capacity must be greater than ZERO (i.e. capacity > 0).If we create a BlockingQueue with ZERO capacity then this will throw java.lang.IllegalArgumentException.


4) Write a program for demonstrating producer & consumer problem using blocking
 queue.

Ans- Find the answer here.


5) What is the difference between ArrayBlockingQueue and LinkedBlockingQueue ?

Ans- ArrayBlockingQueue is a bounded blocking queue backed by an array of objects. LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. 
Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.Linked nodes are dynamically 
created upon each insertion unless this would bring the queue capacity (Integer.MAX_VALUE). 



Follow for more details on @Facebook!!!


Find More Questions & Answers Below.

Producer-Consumer problem solution using java - BlockingQueue

Threading is a very tricky and interesting concept in java programming language. There are many problems we face in technology out of which producer-consumer is one. Today we will write a java program for showing producer consumer problem and its solution by using BlockingQueue implementation. 

In this program we will use ArrayBlockingQueue

FoodProducer.java
package com.javadevelopersguide.lab.concurrent;
import java.util.concurrent.BlockingQueue;
/**
 *
 * @author manoj.bardhan
 *
 */
public class FoodProducer implements Runnable {
private BlockingQueue<String> producerQueue = null;
public FoodProducer(BlockingQueue<String> queue) {
producerQueue = queue;
}
public void run() {
try {
producerQueue.put("Drinks");
Thread.sleep(2000);
producerQueue.put("Chocolates");
Thread.sleep(2000);
producerQueue.put("Fruits");
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


FoodConsumer.java
package com.javadevelopersguide.lab.concurrent;
import java.util.concurrent.BlockingQueue;
/**
 * @author manoj.bardhan
 *
 */
public class FoodConsumer implements Runnable {
private BlockingQueue<String> consumerQueue = null;
public FoodConsumer(BlockingQueue<String> consumerQueue) {
this.consumerQueue = consumerQueue;
}
public void run() {
try {
System.out.println(consumerQueue.take());
System.out.println(consumerQueue.take());
System.out.println(consumerQueue.take());
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}


Now we will have a main class to call and execute these two workers. 

MainFoodProcess.java

package com.javadevelopersguide.lab.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
 *
 * @author manoj.bardhan
 *
 */
public class MainFoodProcess {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
FoodProducer producer = new FoodProducer(queue);
FoodConsumer consumer = new FoodConsumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(3000);
}
}


Output :

Drinks 
Chocolates 
Fruits


The output here is that, every time the producer insert element into the Queue the consumer will take that element out of the queue. 

Here we have used the below 2 important methods take() and put(). There are few many method provided by the BlockingQueue implementation. Find more methods on BlockingQueue.

take() - Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
put() - Inserts the specified element into this queue, waiting if necessary for space to become available.


Happy Learning.






How to get the current location latitude and longitude in java script ?

In this article we will see how to get the latitude and longitude. As we know java script is a high-level programming language,  it gives many libraries to implement in our program to achieve real time necessities.  Here we have used Navigator and Geolocation in our program.

We have used the Navigator.geolocation , its a read-only property returns a Geolocation object that gives Web content access to the location of the device.

sample-geolocation.html

<!DOCTYPE html>
<html>
<body>
<title>Get Current Location Sample</title>
<h4>Click the below button to get your current location coordinates.</h4>
<button onclick="getLocation()">Get My Current Location</button>
<div id="displayId"></div>
<script>
var display = document.getElementById("displayId");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition);
  } else {
    display.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function displayPosition(position) {
  display.innerHTML = "<br>Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>

Now, we can see the output on the browser as below.








Happy Learning.