Showing posts with label Dragging Marker. Show all posts
Showing posts with label Dragging Marker. Show all posts

Aug 12, 2018

Auto Center The Marker With Map Dragging

We used Google Map a lot in our applications. Sometimes in our applications we need select a location from google map. where we can drag the map as well as the marker. I came cross an issue, where I drag the map to select a location which I want, but marker is not responding with that. In order to update the marker with map drag event, we can get the google maps center position and set that to the marker. So when ever we drag the map, marker will auto come to the center of the map. After that we can drag marker as we want.

The below code is an example to do that.


 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
<html>
<head>
    <title>Google Map Auto Center The Marker</title>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
    <div id="map-canvas" style="width:100%;height:500px;"></div>
    Latitude  : <input type="text" id="lat"/>
    Longitude  : <input type="text" id="lng"/>
 
    <script type="text/javascript">
        var lat = 6.929537;  //Your Location Latitude
        var lon = 79.866271; //Your Location Longitude
  
        //Setting Initial Latitide and Longitude
                                  
        document.getElementById("lat").value = lat;
        document.getElementById("lng").value = lon;
   
        var latlng = new google.maps.LatLng(lat, lon);
        var mapOptions = {
            center: latlng,
            zoom: 15
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
  
 google.maps.event.addListener(self.map, "center_changed", function (event) {
    var center = map.getCenter();
    marker.setPosition(center);
        document.getElementById("lat").value = marker.getPosition().lat();
        document.getElementById("lng").value = marker.getPosition().lng();
         });

    </script>
</body>
</html>

Mar 18, 2016

Google Maps Creating Polygon And Retrieving Coordinates

In this article I'm going to explain you about getting the latitude and longitude of a polygon in order to do a google map polygon search. In-order to do that first you should let the user to draw a polygon. Then you should get the latitude and longitude of the corners of the polygon. After getting the latitude and longitude of the area drawn by user, what you have to do is, search it in the database or what ever you want. It's completely up to you.

In this example I'm not telling you guys about the polygon search. I'm just trying to help you in the first step by giving the latitude and longitude array of the drawn area.Following example will help you to develop your own google map.Then you can draw a Polygon area on 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
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
<html>
<head>
    <title>Google Maps Creating Polygon And Retrieving Coordinates</title>
    <script type="text/javascript" src='https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false'></script>
    <style>
        #map-canvas
        {
            width: auto;
            height: 500px;
        }
    </style>
</head>
<body onload="initialize()">
    <div id="map-canvas"></div>
    <div id="result"></div>
    <script type="text/javascript">
        function initialize() {
            var myLatLng = new google.maps.LatLng(6.92814, 79.9124);
            var mapOptions = {
                zoom: 12,
                center: myLatLng
            };
            var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            var triangleCoords = [
                new google.maps.LatLng(6.92814, 79.9124),
                new google.maps.LatLng(6.89746, 79.87636),
                new google.maps.LatLng(6.88553, 79.93644)
            ];

            myPolygon = new google.maps.Polygon({
                paths: triangleCoords,
                draggable: true,
                editable: true,
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FF0000',
                fillOpacity: 0.35
            });

            myPolygon.setMap(map);

            google.maps.event.addListener(myPolygon.getPath(), "insert_at", getPolygonCoords);

            google.maps.event.addListener(myPolygon.getPath(), "set_at", getPolygonCoords);
        }

        function getPolygonCoords() {
            var len = myPolygon.getPath().getLength();
            var htmlStr = "";
            for (var i = 0; i < len; i++) {
                htmlStr += "<p>" + myPolygon.getPath().getAt(i).toUrlValue(5) + "</p>";
            }
            document.getElementById('result').innerHTML = htmlStr;
        }
    </script>
</body>
</html>




Then you can get the coordinates in the selected area. Above example I have draw a triangle so, Ill will get three coordinates. Actually what Google Map returning is the Latitude and Longitude of the corners.


1
myPolygon.getPath().getAt(i).toUrlValue(5);

Above code line returns the Latitude and Longitude of a corner. But if your trying to get a lat-lng object out of it, you cant do it directly. because above methods returns the lat lng as a string. But new google.maps.LatLng(lat,lng) expects two numbers separated with commas. So to do that's follow below lines of codes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function getPolygonCoords() {
    var len = myPolygon.getPath().getLength();
    points = [];
    for (var i = 0; i < len; i++) {
        var strLatLng = myPolygon.getPath().getAt(i).toUrlValue(5);
        var arrLatLng = strLatLng.split(",");
        var objLatLng = new google.maps.LatLng(Number(zzz[0]), Number(zzz[1]));
        points.push(objLatLng);
    }
}

Hope you found this article useful.

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

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

Jul 24, 2015

Getting The Address Of Selected Location In Google Map Using Google Map API v3

Following Example Will Help You To Develop Your Own Google Map To Get The Address Of A Location Including Latitude And Longitude. Before Using Make Sure You have Downloaded The "jquery.gmap3.min.js" Java Script File.


 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
<html>
<head>
    <title>Google Map v3</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false& libraries=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="width: 100%; height: 500px;"></div>
    Street :<input type="text" id="street" />
    City :<input type="text" id="city"/>
    State :<input type="text" id="state" />
    Country :<input type="text" id="country" />
    Latitude :<input type="text" id="lat" />
    Longitude :<input type="text" id="lng"/>

    <script type="text/javascript">

         var componentForm = {
           street_number: 'short_name',
           route: 'long_name',
           locality: 'long_name',
           administrative_area_level_1: 'long_name',
           country: 'long_name'
         };

         var map;
         var lat = 6.929537;//Set Default Latitude To Start
         var lon = 79.866271;//Set Default Longitude To Start
         var str = '[{ "lat" :"' + lat + '","lng" :"' + lon + '"}]';
         str = JSON.parse(str);
       
         jQuery('#map-canvas').gmap3({
            marker: {
               values: str,
               options: {
                 icon:'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
                 draggable:true
               },
               events:{
                 dragend: function(marker){
                   $('#lat').val(marker.getPosition().lat());
                   $('#lng').val(marker.getPosition().lng());
                   $(this).gmap3({
                     getaddress:{
                       latLng:marker.getPosition(),
                       callback:function(results){
                         printAddress(results[0]);
                       }
                     }
                   });
                 }
               },
            },
            map: {
               options: {
                 zoom: 14,
                 scrollwheel: true,
                 streetViewControl: true
               }
            }
        });

        function printAddress(place){
            var streetnumber = "";
            var streetname = "";
            for (var i = 0; i < place.address_components.length; i++) {
                var addressType = place.address_components[i].types[0];
                if(addressType == "street_number"){
                  streetnumber = place.address_components[i][componentForm[addressType]];
                }else if(addressType == "route"){
                  streetname = place.address_components[i][componentForm[addressType]];
                }else if(addressType == "locality"){
                  $("#city").val(place.address_components[i][componentForm[addressType]]);
                }else if(addressType == "administrative_area_level_1"){
                  $("#state").val(place.address_components[i][componentForm[addressType]]);
                }else if(addressType == "country"){
                  $("#country").val(place.address_components[i][componentForm[addressType]]);
                }
                if(streetnumber != "" && streetname !=""){
                  $("#street").val(streetnumber + " , " + streetname);
                }
                else{
                  $("#street").val(streetnumber + streetname);
                }
            }
        }
    </script>
</body>
</html>




This Is Simple Example That Gets You The Address Of A Selected Place Using Google Map.You Can Drag The Marker Position As You Want.Then It Will Get You The Updated Marker Position And It Will Give You The Address Of The Location.This Uses A 'Dragend' Function.There Are Lot Of Functions Associated With Google Maps.


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 Selected Latitude And Longitude From Google Map Using Google Map API v3

Following example will help you to create a Google Map which has picker to find the latitude and longitude.

 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
<html>
  <head> 
    <title>Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3</title> 
    <script type="text/javascript" src='https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false'></script>
  </head> 
  <body>
    <div id="map-canvas" style="width:100%;height:500px;"></div>
    Latitude  : <input type="text" id="lat"/>
    Longitude  : <input type="text" id="lng"/>
   
    <script type="text/javascript">
        var lat = 6.929537; //Your Location Latitude
        var lon = 79.866271; //Your Location Longitude
        var latlng = new google.maps.LatLng(lat, lon);
        var mapOptions = {
            center: latlng,
            zoom: 15
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            draggable: true
        });

        google.maps.event.addListener(marker, "dragend", function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
  
    </script>
  </body>
</html>




This Is Simple Example That Shows The Given Location Using A Marker.You Can Drag The Marker Position As You Want.Then It Will Get You The Updated Marker Position.This Uses A 'Dragend' Function.There Are Lot Of Functions Associated With Google Maps.


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...