Sunday, 10 November 2019

Drag Pushpin on Bing Map - JavaScript

Hi,

Today, we have got some requirement where the users should be able to drag the Pin on the Map and we should get the Latitude and Longitude of that position.

We have to use "dragend" event for it.

Here is the full html of the same. Just replace BING-MAP-KEY with your Bing Map Key.


<html>
<head>
    <title>Drag Pushpin</title>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <style type='text/css'>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            font-family: 'Segoe UI',Helvetica,Arial,Sans-Serif;
        }
    </style>
</head>
<body>
    <div id='printoutPanel'></div>
    <div id='divLatitudeUp'></div>
    <div id='divLongitudeUp'></div>
    <div id='myMap'></div>
    <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=BING-MAP-KEY&callback=loadMapScenario' async defer></script>
    <script type='text/javascript'>
        var zoomLevel = 10;
        var map;
        function handleArgs(id, e) {
            var point = new Microsoft.Maps.Point(e.getX(), e.getY());
            var loc = e.target.getLocation();;
            var location = new Microsoft.Maps.Location(loc.latitude, loc.longitude);
            if (id == "pushpinDragEnd") {
                document.getElementById("divLatitudeUp").innerHTML = "Latitude : " + loc.latitude;
                document.getElementById("divLongitudeUp").innerHTML = "Longitude : " + loc.longitude;
            }
        }

        function loadMapScenario() {
            var map = new Microsoft.Maps.Map(document.getElementById('myMap'), { zoom: zoomLevel });
            var center = map.getCenter();
            var Events = Microsoft.Maps.Events;
            var Location = Microsoft.Maps.Location;
            var Pushpin = Microsoft.Maps.Pushpin;
            var loc = new Location(center.latitude, center.longitude);

            var dragablePushpin = new Pushpin(loc, { color: '#00F', draggable: true });
            map = new Microsoft.Maps.Map(document.getElementById('myMap'), { center: loc, zoom: zoomLevel });
            Events.addHandler(dragablePushpin, 'dragend', function (e) { handleArgs('pushpinDragEnd', e); });
            map.entities.push(dragablePushpin);
        }

    </script>
</body>

</html>


Hope this helps.

--
Happy Coding
Gopinath

No comments:

Post a Comment