Mapview Adding Pushpins on Touch

Introduction

This article will guide you through creating an interactive map using the Bing Maps V8 JavaScript API, where pushpins are added to the map when the user touches the map surface.

Prerequisites

  • Basic understanding of HTML, CSS, and JavaScript.
  • Bing Maps V8 API Key: Register for a free Bing Maps API key from here.

HTML Structure

<!DOCTYPE html>
<html>
<head>
<title>Bing Maps Pushpin on Touch</title>
<meta charset="UTF-8">
<script src="https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=YOUR_BING_MAPS_API_KEY"></script>
<style>
#myMap {
  height: 500px;
  width: 100%;
}
</style>
</head>
<body>
<div id="myMap"></div>
<script>
// JavaScript code will go here
</script>
</body>
</html>

JavaScript Implementation

<script>
function GetMap() {
  var map = new Microsoft.Maps.Map('#myMap', {
    center: new Microsoft.Maps.Location(47.6062, -122.3321),
    zoom: 10
  });

  // Event Listener for touch event on the map
  Microsoft.Maps.Events.addHandler(map, 'click', function(e) {
    // Add a pushpin at the clicked location
    var pushpin = new Microsoft.Maps.Pushpin(e.location, {
      title: 'Touched Location',
      text: 'New Pin',
      icon: 'https://www.bingmapsportal.com/Content/images/mapicons/pushpin_blue.png'
    });
    map.entities.push(pushpin);
  });
}
</script>

Explanation

  • GetMap Function: This function is called by the Bing Maps API once the script has loaded.
  • Map Initialization: A new map instance is created with an initial center point (Seattle) and zoom level.
  • Click Event Handler: The ‘click’ event is used to capture user touch events on the map.
  • Pushpin Creation: A new pushpin is created at the location clicked on the map.
  • Pushpin Properties: The pushpin is configured with a title, text, and an optional icon.
  • Adding Pushpin to Map: The pushpin is added to the map’s entities collection.

Output

When you run this code, you’ll see a Bing Maps interactive map. On touch, a blue pushpin with a title and text will be added to the map.

Customization

  • Location: Change the initial map center and zoom to display a different location.
  • Pushpin Appearance: Customize the pushpin’s icon, title, and text.
  • Event Handling: Use different map events (e.g., mouseover, mouseout) to trigger other actions.

Conclusion

This article provides a foundation for adding pushpins on touch in your Bing Maps applications. By understanding the basic principles, you can easily customize and extend this functionality to meet your specific needs.

Leave a Reply

Your email address will not be published. Required fields are marked *