Easy Google Maps Marker Manager
Click the map to add new marker and right click to this marker to remove it.
by oterox
HTML
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB6YAqeEFMu0ohvdr8h2Z6jhJW17pQSeII&sensor=false"></script>
<div id="map"></div>
CSS
#map{
width: 600px;
height: 600px;
}
JavaScript
/**
* @author : Fatih Acet <[email protected]>
* @date : Dec 15, 2011
* @description : An easy and quick demonstation about marker management in Google Maps.
* This demo creates a new map and binds click event to map.
* In every click event new marker appends to map. To remove the marker simply right click it.
*/
/**
* Create new map
*/
var map;
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(36.87916, -4.32910),
mapTypeId: 'roadmap'
};
map = new google.maps.Map($('#map')[0], myOptions);
/**
* Global marker object that holds all markers.
* @type {Object.<string, google.maps.LatLng>}
*/
var markers = {};
/**
* Concatenates given lat and lng with an underscore and returns it.
* This id will be used as a key of marker to cache the marker in markers object.
* @param {!number} lat Latitude.
* @param {!number} lng Longitude.
* @return {string} Concatenated marker id.
*/
var getMarkerUniqueId= function(lat, lng) {
return lat + '_' + lng;
}
/**
* Creates an instance of google.maps.LatLng by given lat and lng values and returns it.
* This function can be useful for getting new coordinates quickly.
* @param {!number} lat Latitude.
* @param {!number} lng Longitude.
* @return {google.maps.LatLng} An instance of google.maps.LatLng object
*/
var getLatLng = function(lat, lng) {
return new google.maps.LatLng(lat, lng);
};
/**
* Binds click event to given map and invokes a callback that appends a new marker to clicked location.
*/
var addMarker = google.maps.event.addListener(map, 'click', function(e) {
var lat = e.latLng.lat(); // lat of clicked point
var lng = e.latLng.lng(); // lng of clicked point
var markerId = getMarkerUniqueId(lat, lng); // an that will be used to cache this marker in markers object.
var marker = new google.maps.Marker({
position: getLatLng(lat, lng),
map: map,
id: 'marker_' + markerId
});
...