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>

No comments:

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