Oct 17, 2015

Getting The Direction Between Two Markers In Google Map Using Google MAP API

In this article I'm going to show guys to get the direction between two locations. In-order to do that I have created a simple html page consisting google map with two markers. You can drag the markers as you wish. In the page below the map I have shown the selected locations Latitude and Longitude. After moving the markers you will get the direction.

Have a look on the code. It's simply created using Html and JavaScript.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<html>
<head>
    <title>Getting The Direction Between Two Markers In Google Map Using Google MAP API</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
</head>
<body>
    <div id="map-canvas" style="height: 75%;"></div>
    <div>
        <strong>From Location</strong><br />
        <span>Latitude : </span>
        <input type="text" id="fromLat" />
        <span>Longitude : </span>
        <input type="text" id="fromLng" />
        <br /><br />
        
        <strong>To Location</strong><br />
        <span>Latitude : </span>
        <input type="text" id="toLat" />
        <span>Longitude : </span>
        <input type="text" id="toLng" />
        <br /><br />

        <div id="direction"></div>
    </div>
    <script type="text/javascript">
        var map;
        var fromLat = 6.928940573589038;
        var fromLng = 79.87219331750487;
        var toLat = 6.929110981212029;
        var toLng = 79.87013338098143;

        var fromIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
        var toIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';

        loadMap();
        setFromMarker();
        setToMarker();

        function loadMap() {
            map = new google.maps.Map(document.getElementById('map-canvas'), {
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: new google.maps.LatLng(fromLat, fromLng),
                zoom: 15
            });
        }

        function setFromMarker() {
            var fromMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(fromLat, fromLng),
                icon: fromIcon,
                animation: google.maps.Animation.DROP,
                draggable: true
            });

            google.maps.event.addListener(fromMarker, 'dragend', function (event) {
                fromLat = event.latLng.lat();
                fromLng = event.latLng.lng();
                setLatLngDetails();
            });
        }

        function setToMarker() {
            var toMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(toLat, toLng),
                icon: toIcon,
                animation: google.maps.Animation.DROP,
                draggable: true
            });

            google.maps.event.addListener(toMarker, 'dragend', function (event) {
                toLat = event.latLng.lat();
                toLng = event.latLng.lng();
                setLatLngDetails();
            });
        }

        function setLatLngDetails() {
            $("#fromLat").val(fromLat);
            $("#fromLng").val(fromLng);
            $("#toLat").val(toLat);
            $("#toLng").val(toLng);
            getDirection();
        }

        function getDirection() {
            var fromLocation = new google.maps.LatLng(fromLat, fromLng);
            var toLocation = new google.maps.LatLng(toLat, toLng);
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins: [fromLocation],
                destinations: [toLocation],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, callback_direction);
        }

        function callback_direction(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
                alert('Error was: ' + status);
            } else {
                var origins = response.originAddresses;
                var destinations = response.destinationAddresses;
                var str = '';

                for (var i = 0; i < origins.length; i++) {
                    var results = response.rows[i].elements;
                    if (results[0].status != 'ZERO_RESULTS') {
                        for (var j = 0; j < results.length; j++) {
                            str += origins[i] + '<strong> to </strong>' + destinations[j] + '<strong> : </strong>' + results[j].distance.text + '<strong> in </strong>' + results[j].duration.text + '<br/>';
                        }
                    } else {
                        str = 'No Direction Found.';
                    }
                }

                $("#direction").html(str);
            }
        }
   
    </script>
</body>
</html>

When you are getting the direction between two locaions, you must specify the mode of the travel. Following are the travel modes supported by google.
  • google.maps.TravelMode.DRIVING (Default) indicates standard driving directions using the road network.
  • google.maps.TravelMode.BICYCLING requests bicycling directions via bicycle paths & preferred streets.
  • google.maps.TravelMode.TRANSIT requests directions via public transit routes.
  • google.maps.TravelMode.WALKING requests walking directions via pedestrian paths & sidewalks.




Check My Other Articles About Google Maps.

1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates

Getting The Direction Between Two Locations Using Google MAP API

In this article I'm going to show guys to get the direction between two locations. In-order to do that I have created a simple html page consisting four text fields to enter the from locations and to locations latitude and longitude. You can enter the locations latitude and longitudes of from and to locations and click the "Get Direction" button. After clicking the button you will get the direction.

Have a look on the code. It's simply created using Html and JavaScript.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<html>
 <head>
  <title>Getting The Direction Between Two Locations Using Google MAP API</title>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
 </head>
 <body> 
  <div>
   <strong>From Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="fromLat"/>
   <span>Longitude : </span>
   <input type="text" id="fromLng"/>
   <br/><br/>

   <strong>To Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="toLat"/>
   <span>Longitude : </span>
   <input type="text" id="toLng"/>
   <br/><br/>

   <input type="button" value="Get Direction" onclick="getDirection()"/>
   <br/><br/>
   <div id="direction"></div>
  </div>
  
  <script type="text/javascript">

      function getDirection() {
          var fromLocation = new google.maps.LatLng($("#fromLat").val(), $("#fromLng").val());
          var toLocation = new google.maps.LatLng($("#toLat").val(), $("#toLng").val());
          var service = new google.maps.DistanceMatrixService();
          service.getDistanceMatrix({
              origins: [fromLocation],
              destinations: [toLocation],
              travelMode: google.maps.TravelMode.DRIVING,
              unitSystem: google.maps.UnitSystem.METRIC,
              avoidHighways: false,
              avoidTolls: false
          }, callback_direction);
      }

      function callback_direction(response, status) {
          if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: ' + status);
          } else {
              var origins = response.originAddresses;
              var destinations = response.destinationAddresses;
              var str = '';

              for (var i = 0; i < origins.length; i++) {
                  var results = response.rows[i].elements;
                  if (results[0].status != 'ZERO_RESULTS') {
                      for (var j = 0; j < results.length; j++) {
                          str += origins[i] + '<strong> to </strong>' + destinations[j] + '<strong> : </strong>' + results[j].distance.text + '<strong> in </strong>' + results[j].duration.text + '<br/>';
                      }
                  } else {
                      str = 'No Direction Found.';
                  }
              }

              $("#direction").html(str);
          }
      }
  </script>
 </body>
</html> 

Just check the code in browser, you will get the following output.


When you are getting the direction between two locaions, you must specify the mode of the travel. Following are the travel modes supported by google.
  • google.maps.TravelMode.DRIVING (Default) indicates standard driving directions using the road network.
  • google.maps.TravelMode.BICYCLING requests bicycling directions via bicycle paths & preferred streets.
  • google.maps.TravelMode.TRANSIT requests directions via public transit routes.
  • google.maps.TravelMode.WALKING requests walking directions via pedestrian paths & sidewalks.


Check My Other Articles About Google Maps.

1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates

Getting The Distance Between Two Markers In Google Map Using Google MAP API

In this article I'm going to show guys to get the distance between two locations. Please note that, this is not the direction distance. That mean if you select two locations you will get distance, which is going to very less than the travel distance. In-order to do that I have created a simple html page consisting google map with two markers. You can drag the markers as you wish. In the page below the map I have shown the selected locations Latitude and Longitude. After moving the markers you will get the distance.

Have a look on the code. It's simply created using Html and JavaScript.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
<html>
 <head>
  <title>Getting The Distance Between Two Markers In Google Map Using Google MAP API</title>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
 </head>
 <body> 
  <div id="map-canvas" style="height:75%;"></div>
  <div>
   <strong>From Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="fromLat"/>
   <span>Longitude : </span>
   <input type="text" id="fromLng"/>
   <br/><br/>

   <strong>To Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="toLat"/>
   <span>Longitude : </span>
   <input type="text" id="toLng"/>
   <br/><br/>

   <strong>Distance : </strong>
   <span id="distance">0.00</span>
   <span> meters</span>
  </div>
  <script type="text/javascript">
      var map;
      var fromLat = 6.928940573589038;
      var fromLng = 79.87219331750487;
      var toLat = 6.929110981212029;
      var toLng = 79.87013338098143;

      var fromIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
      var toIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';

      loadMap();
      setFromMarker();
      setToMarker();

      function loadMap() {
          map = new google.maps.Map(document.getElementById('map-canvas'), {
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              center: new google.maps.LatLng(fromLat, fromLng),
              zoom: 15
          });
      }

      function setFromMarker() {
          var fromMarker = new google.maps.Marker({
              map: map,
              position: new google.maps.LatLng(fromLat, fromLng),
              icon: fromIcon,
              animation: google.maps.Animation.DROP,
              draggable: true
          });

          google.maps.event.addListener(fromMarker, 'dragend', function (event) {
              fromLat = event.latLng.lat();
              fromLng = event.latLng.lng();
              setLatLngDetails();
          });
      }

      function setToMarker() {
          var toMarker = new google.maps.Marker({
              map: map,
              position: new google.maps.LatLng(toLat, toLng),
              icon: toIcon,
              animation: google.maps.Animation.DROP,
              draggable: true
          });

          google.maps.event.addListener(toMarker, 'dragend', function (event) {
              toLat = event.latLng.lat();
              toLng = event.latLng.lng();
              setLatLngDetails();
          });
      }

      function setLatLngDetails() {
          $("#fromLat").val(fromLat);
          $("#fromLng").val(fromLng);
          $("#toLat").val(toLat);
          $("#toLng").val(toLng);
          getDistance();
      }

      function getDistance() {
          var fromLocation = new google.maps.LatLng(fromLat, fromLng);
          var toLocation = new google.maps.LatLng(toLat, toLng);

          var distance = google.maps.geometry.spherical.computeDistanceBetween(fromLocation, toLocation).toFixed(2);
          $("#distance").html(distance);
      }
   
  </script>
 </body>
</html> 

Simply copy and paste the above codes in a text editor and it in a browser. You will get the below outputs.




If you carefully read the above code, you will know that I have initialized the from and to locations. If you want to make this code more efficient way, where you want to get the user location as default location. Click Here to check the article. 

Check My Other Articles About Google Maps.

1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates

Restrict To Enter Only Decimal Using Java Script

In this article I'm going to show guys, how to restrict a text field only to enter decimal values. And most importantly you can tell the function how many decimal places you want to restrict.

Have a look on the code. It's simply created using Html and JavaScript.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<html>
<body>
    <label>One Decimal Only</label>
    <input type="text" onpaste="return false" onkeypress="return restrictToDecimal(this,event,1)" />
    <br />

    <label>Two Decimal Only</label>
    <input type="text" onpaste="return false" onkeypress="return restrictToDecimal(this,event,2)" />
    <br />

    <label>Five Decimal Only</label>
    <input type="text" onpaste="return false" onkeypress="return restrictToDecimal(this,event,5)" />
</body>
<script type="text/javascript">
    function restrictToDecimal(el, evt, dec) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        var number = el.value.split('.');
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        //Restrict To Enter One Period
        if (number.length > 1 && charCode == 46) {
            return false;
        }

        //Getting The Character Position Entered
        var caratPos = getSelectionStart(el);
        var dotPos = el.value.indexOf(".");
        if (caratPos > dotPos && dotPos > -1 && (number[1].length > dec - 1)) {
            return false;
        }

        return true;
    }

    function getSelectionStart(o) {
        if (o.createTextRange) {
            var r = document.selection.createRange().duplicate()
            r.moveEnd('character', o.value.length)
            if (r.text == '') return o.value.length
            return o.value.lastIndexOf(r.text)
        } else return o.selectionStart
    }
</script>
</html>

If you want use following single JavaScript to do it.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function restrictToDecimal(el, evt, dec) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }

    //Restrict To Enter One Period
    if (number.length > 1 && charCode == 46) {
        return false;
    }

    //Getting The Character Position Entered
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if (caratPos > dotPos && dotPos > -1 && (number[1].length > dec - 1)) {
        return false;
    }

    return true;

    function getSelectionStart(o) {
        if (o.createTextRange) {
            var r = document.selection.createRange().duplicate()
            r.moveEnd('character', o.value.length)
            if (r.text == '') return o.value.length
            return o.value.lastIndexOf(r.text)
        } else return o.selectionStart
    }

}

Bind Data Source To A DataGridView In Windows Form Application With Sql Server

In This Article Ill Demonstrate You Guys To Integrate A SQL Server Data Source With Data Grid View In C# Using Step By Step. In This Article I Will Create A Windows Form Application To Integrate With SQL Server. First Of All Make Sure You Have Installed SQL Server.

So Lets Start Our Application By Opening The Visual Studio. 

Step 01 : Click New Project And Select Windows > Windows Forms Application And Give A Project Name To It. Just Have A Look On Below Image, It Shows How I Did. 


Now Press OK And Create The Project. Then Open The Toolbox. If Toolbox Not Visible Click View > Toolbox. Then Toolbox Window Will Open. Then Add A Data Grid View From Tool Box To The Form.

Now What We Need To Do Is We Should Connect The DataGridView With SQL Server Data Source. Follow The Below Steps Continue It.

Step 02 : Open Server Explorer.



 Step 03 : Add A New Data Connection By Right Clicking The Data Connections Tab.



Step 04 : Select The Data Source As "Microsoft SQL Server (SqlClient)" And Select The Server Name. According To SQL Server, Select The Logging Either Windows Authentication Or SQL Server Authentication. Then Enter The Database Name. In My Example I Wanted My Database Name As "Bind Data To A GridView". If You Already Have A Database You Can Simply Select Your Database From Here. But Here I Will Create A New Database. Then Press OK.


Step 05 : If You Enter A Database Which Is Not Existing, It Will Open A Popup Like Below. Press Yes To Create It.


Step 06 : Then You Will Get The Server Explorer As Below. Right Click Tables And Add A New Table If You Created A New Database.



Step 07 : I Have Created The Table Called Employee With The Following Fields. Then Click Update Button.



Step 08 : Go To SQL Server And Check The Database With The Table We Have Created.



Step 09 : Add Some Sample Data To The Table To Test The Data Source.



Step 10 : Add Data Source To The Data Grid View.



Step 11 : Select The Source Type As Database.



Step 12 : Choose The Database Model



Step 13 : Choose The Connection



Step 14 : Give A Name To The Connection



Step 15 : Select The Table And Columns You Want To Show.



Now You Will See The Data Grid As Below.



Now Run The Project And Check The Output.


Hope You Got The Basic Knowledge And Enjoyed.


Aug 13, 2015

Getting The Distance Between Two Locations Using Google MAP API

Following example will help you to get distance between two location using 'googleapi' in java script. Please note that this is distance between two location. This is not the direction to travel or something.

Now lets have a look on code. In this example I have created four text fields to get the Latitude and Longitude of from location and To location.

I have used the online java script library of google map api library.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<html>
 <head>
  <title>Getting The Distance Between Two Locations Using Google MAP API</title>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
 </head>
 <body> 
  <div>
   <strong>From Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="fromLat"/>
   <span>Longitude : </span>
   <input type="text" id="fromLng"/>
   <br/><br/>

   <strong>To Location</strong><br/>
   <span>Latitude : </span>
   <input type="text" id="toLat"/>
   <span>Longitude : </span>
   <input type="text" id="toLng"/>
   <br/><br/>

   <input type="button" value="Calculate Distance" onclick="getDistance()"/>
   <br/><br/>

   <strong>Distance : </strong>
   <span id="distance">0.00</span>
   <span> meters</span>
  </div>
  <script type="text/javascript">
      function getDistance() {
          var fromLocation = new google.maps.LatLng($("#fromLat").val(), $("#fromLng").val());
          var toLocation = new google.maps.LatLng($("#toLat").val(), $("#toLng").val());
          var distance = google.maps.geometry.spherical.computeDistanceBetween(fromLocation, toLocation).toFixed(2);
          $("#distance").html(distance);
      }
  </script>
 </body>
</html> 

Just copy the code and create a html file and open in the browser. Enter the Latitude and Longitude of From and To locations and click the 'Calculate Distance' button.



If you want you can improve the code by sending the Latitude and Longitude of From and To locations by using a method and get the distance.



Check My Other Articles About Google Maps.

1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates

Getting The Nearest Places For A Location In Google Map Using Google MAP API

Following example will help you to develop your own 'Google Map' to get the nearest places of a location by latitude and longitude using java script.

"mylocation" variables contains the location you want to search for places. In this example first it will load the map and center it to your given latitude and longitude. After loading the map it will create the marker in the map of the location searched. This is happening in the "setCurrentLocation()" function. If you want, you can get rid of this method, if you don't want to show your location on the map.

Then we should request details from " google.maps.places.PlacesService". In the request you should specify your location and types. In my example I have used types such as 'train_station', 'bus_station' and 'subway_station'.You can find more types here.

In the request I have specified another parameter called 'rankBy'. This will sort the results your getting. In my example I have specified 'google.maps.places.RankBy.DISTANCE', which will sort the results by nearest to the place search.

Now lets have a look on code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<html>
<head>
    <title>Getting The Nearest Places For A Location In Google Map Using Google MAP API</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
</head>
<body>
    <div id="map-canvas" style="height: 100%;"></div>
    <script type="text/javascript">
        var map;
        var infowindow;
        var service ;
        var mylocation = new google.maps.LatLng(6.928940573589038, 79.87219331750487);
        //Set Your Current Location to 'mylocation'
        getGooglePlaces();

        function getGooglePlaces(lat,lng)
        {      
            //load the map
            map = new google.maps.Map(document.getElementById('map-canvas'), {
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: mylocation,
                zoom: 15
            });
     
            infowindow = new google.maps.InfoWindow();
            service = new google.maps.places.PlacesService(map);
    
            setCurrentLocation();
  
            var request = {
                location: mylocation,
                rankBy: google.maps.places.RankBy.DISTANCE,
                types: ['train_station','bus_station','subway_station'] 
                //More Types From
                //https://developers.google.com/places/supported_types
            };
            service.search(request, callback_googlePlaces);
        }
   
        function setCurrentLocation() {
            var marker = new google.maps.Marker({
                map: map,
                position: mylocation,
                icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000',
                animation: google.maps.Animation.DROP
            });

            google.maps.event.addListener(marker, 'click', function() {
                var content='<strong>Current Place</strong>';
                infowindow.setContent(content);
                infowindow.open(map, this);
            });
        }

        function callback_googlePlaces(results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                for (var i = 0; i < results.length; i++) {
                    createMarker(results[i]);
                }
            }
        }

        function createMarker(place) {
            var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location,
                animation: google.maps.Animation.DROP
            });
    
            google.maps.event.addListener(marker, 'click', function() {
                var content='<strong>' + place.name + '</strong><br/>' + '<span>' + place.vicinity + '</span><br/>' + '<span>' + place.types[0] + '</span><br/>' + '<span>' + google.maps.geometry.spherical.computeDistanceBetween(mylocation, place.geometry.location).toFixed(2) + ' meters</span>';
                infowindow.setContent(content);
                infowindow.open(map, this);
            });
        } 
   
    </script>
</body>
</html>

In this example I have used the 'googleapis' online. So no need to include any java script files. Copy the code and save as a html file. Just open the file in the browser. You will see the below result.




If you click the marker you will get a info window which shows you the distance.
Please note that this distance is direct distance. This is not the direction distance.
That mean travelling distance.

Check My Other Articles About Google Maps.

1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...