Taken from http://stackoverflow.com/questions/1538681/how-to-call-fromlatlngtodivpixel-in-google-maps-api-v3/12026134#12026134 and modified to use Leaflet API
182846
function getExtendedBounds(map, bounds, gridSize) {
  // Turn the bounds into latlng.
  var northEastLat = bounds && bounds.getNorthEast() && bounds.getNorthEast().lat;
  var northEastLng = bounds && bounds.getNorthEast() && bounds.getNorthEast().lng;
  var southWestLat = bounds && bounds.getSouthWest() && bounds.getSouthWest().lat;
  var southWestLng = bounds && bounds.getSouthWest() && bounds.getSouthWest().lng;

  var tr = _leaflet2.default.latLng(northEastLat, northEastLng);
  var bl = _leaflet2.default.latLng(southWestLat, southWestLng);

  // Convert the points to pixels and the extend out by the grid size.
  var trPix = map.latLngToLayerPoint(tr);
  trPix.x += gridSize;
  trPix.y -= gridSize;

  var blPix = map.latLngToLayerPoint(bl);
  blPix.x -= gridSize;
  blPix.y += gridSize;

  // Convert the pixel points back to LatLng
  var ne = map.layerPointToLatLng(trPix);
  var sw = map.layerPointToLatLng(blPix);

  // Extend the bounds to contain the new bounds.
  bounds.extend(ne);
  bounds.extend(sw);

  return bounds;
}
943612
function (position) {
        if (position instanceof OpenLayers.Bounds) {
            var bounds,
                targetCenterPx = position.getCenterPixel();
            if (!this.out) {
                var minXY = this.map.getLonLatFromPixel({
                    x: position.left,
                    y: position.bottom
                });
                var maxXY = this.map.getLonLatFromPixel({
                    x: position.right,
                    y: position.top
                });
                bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat,
                                               maxXY.lon, maxXY.lat);
            } else {
                var pixWidth = position.right - position.left;
                var pixHeight = position.bottom - position.top;
                var zoomFactor = Math.min((this.map.size.h / pixHeight),
                    (this.map.size.w / pixWidth));
                var extent = this.map.getExtent();
                var center = this.map.getLonLatFromPixel(targetCenterPx);
                var xmin = center.lon - (extent.getWidth()/2)*zoomFactor;
                var xmax = center.lon + (extent.getWidth()/2)*zoomFactor;
                var ymin = center.lat - (extent.getHeight()/2)*zoomFactor;
                var ymax = center.lat + (extent.getHeight()/2)*zoomFactor;
                bounds = new OpenLayers.Bounds(xmin, ymin, xmax, ymax);
            }
            // always zoom in/out 
            var lastZoom = this.map.getZoom(),
                size = this.map.getSize(),
                centerPx = {x: size.w / 2, y: size.h / 2},
                zoom = this.map.getZoomForExtent(bounds),
                oldRes = this.map.getResolution(),
                newRes = this.map.getResolutionForZoom(zoom);
            if (oldRes == newRes) {
                this.map.setCenter(this.map.getLonLatFromPixel(targetCenterPx));
            } else {
              var zoomOriginPx = {
                    x: (oldRes * targetCenterPx.x - newRes * centerPx.x) /
                        (oldRes - newRes),
                    y: (oldRes * targetCenterPx.y - newRes * centerPx.y) /
                        (oldRes - newRes)
                };
                this.map.zoomTo(zoom, zoomOriginPx);
            }
            if (lastZoom == this.map.getZoom() && this.alwaysZoom == true){ 
                this.map.zoomTo(lastZoom + (this.out ? -1 : 1)); 
            }
        } else if (this.zoomOnClick) { // it's a pixel
            if (!this.out) {
                this.map.zoomTo(this.map.getZoom() + 1, position);
            } else {
                this.map.zoomTo(this.map.getZoom() - 1, position);
            }
        }
    }
128717
function(terria, map) {
  GlobeOrMap.call(this, terria);

  /**
   * Gets or sets the Leaflet {@link Map} instance.
   * @type {Map}
   */
  this.map = map;

  this.scene = new LeafletScene(map);

  /**
   * Gets or sets whether this viewer _can_ show a splitter.
   * @type {Boolean}
   */
  this.canShowSplitter = true;

  /**
   * Gets the {@link LeafletDataSourceDisplay} used to render a {@link DataSource}.
   * @type {LeafletDataSourceDisplay}
   */
  this.dataSourceDisplay = undefined;

  this._tweens = new TweenCollection();
  this._tweensAreRunning = false;
  this._selectionIndicatorTween = undefined;
  this._selectionIndicatorIsAppearing = undefined;

  this._pickedFeatures = undefined;
  this._selectionIndicator = L.marker([0, 0], {
    icon: L.divIcon({
      className: "",
      html:
        '<img src="' +
        selectionIndicatorUrl +
        '" width="50" height="50" alt="" />',
      iconSize: L.point(50, 50)
    }),
    zIndexOffset: 1, // We increment the z index so that the selection marker appears above the item.
    interactive: false,
    keyboard: false
  });
  this._selectionIndicator.addTo(this.map);
  this._selectionIndicatorDomElement = this._selectionIndicator._icon.children[0];

  this._dragboxcompleted = false;
  this._pauseMapInteractionCount = 0;

  this.scene.featureClicked.addEventListener(
    featurePicked.bind(undefined, this)
  );

  var that = this;

  // if we receive dragboxend (see LeafletDragBox) and we are currently
  // accepting a rectangle, then return the box as the picked feature
  map.on("dragboxend", function(e) {
    var mapInteractionModeStack = that.terria.mapInteractionModeStack;
    if (
      defined(mapInteractionModeStack) &&
      mapInteractionModeStack.length > 0
    ) {
      if (
        mapInteractionModeStack[mapInteractionModeStack.length - 1]
          .drawRectangle &&
        defined(e.dragBoxBounds)
      ) {
        var b = e.dragBoxBounds;
        mapInteractionModeStack[
          mapInteractionModeStack.length - 1
        ].pickedFeatures = Rectangle.fromDegrees(
          b.getWest(),
          b.getSouth(),
          b.getEast(),
          b.getNorth()
        );
      }
    }
    that._dragboxcompleted = true;
  });

  map.on("click", function(e) {
    if (!that._dragboxcompleted && that.map.dragging.enabled()) {
      pickFeatures(that, e.latlng);
    }
    that._dragboxcompleted = false;
  });

  this._selectedFeatureSubscription = knockout
    .getObservable(this.terria, "selectedFeature")
    .subscribe(function() {
      selectFeature(this);
    }, this);

  this._splitterPositionSubscription = knockout
    .getObservable(this.terria, "splitPosition")
    .subscribe(function() {
      this.updateAllItemsForSplitter();
    }, this);

  this._showSplitterSubscription = knockout
    .getObservable(terria, "showSplitter")
    .subscribe(function() {
      this.updateAllItemsForSplitter();
    }, this);

  map.on("layeradd", function(e) {
    that.updateAllItemsForSplitter();
  });

  map.on("move", function(e) {
    that.updateAllItemsForSplitter();
  });

  this._initProgressEvent();

  selectFeature(this);
}
1334870
function () {
        // -- todo make the viewInfo properties  flat objects.
        var size = this._map.getSize();
        var bounds = this._map.getBounds();
        var zoom = this._map.getZoom();

        var center = this.LatLonToMercator(this._map.getCenter());
        var corner = this.LatLonToMercator(this._map.containerPointToLatLng(this._map.getSize()));

        var del = this._delegate || this;
        del.onDrawLayer && del.onDrawLayer({
            layer: this,
            canvas: this._canvas,
            bounds: bounds,
            size: size,
            zoom: zoom,
            center: center,
            corner: corner
        });
        this._frame = null;
    }
784571
function(layer) {
    var me          = this.toJSON()
      , other       = layer.toJSON()
      // Select params generated when layer is added to the map
      , map_params  = ['id', 'order'];

    // Delete from the layers copy
    _.each(map_params, function(param){
      delete me[param];
      delete other[param];
      if (me.options)     delete me.options[param];
      if (other.options)  delete other.options[param];
    });

    var myType  = me.type? me.type : me.options.type
      , itsType = other.type? other.type : other.options.type;

    if(myType && (myType === itsType)) {

      if(myType === 'Tiled') {
        var myTemplate  = me.urlTemplate? me.urlTemplate : me.options.urlTemplate;
        var itsTemplate = other.urlTemplate? other.urlTemplate : other.options.urlTemplate;
        var myName = me.name? me.name : me.options.name;
        var itsName = other.name? other.name : other.options.name;

        return myTemplate === itsTemplate && myName === itsName;
      } else if(myType === 'WMS') {
        var myTemplate  = me.urlTemplate? me.urlTemplate : me.options.urlTemplate;
        var itsTemplate = other.urlTemplate? other.urlTemplate : other.options.urlTemplate;
        var myLayer  = me.layers? me.layers : me.options.layers;
        var itsLayer = other.layers? other.layers : other.options.layers;
        return myTemplate === itsTemplate && myLayer === itsLayer;
      }
      else if (myType === 'torque') {
        return cdb.geo.TorqueLayer.prototype.isEqual.call(this, layer);
      }
      else if (myType === 'named_map') {
        return cdb.geo.CartoDBNamedMapLayer.prototype.isEqual.call(this, layer);
      } else { // same type but not tiled
        var myBaseType = me.base_type? me.base_type : me.options.base_type;
        var itsBaseType = other.base_type? other.base_type : other.options.base_type;
        if(myBaseType) {
          if(_.isEqual(me,other)) {
            return true;
          } else {
            return false;
          }
        } else { // not gmaps
          return true;
        }
      }
    }
    return false; // different type
  }
194532
function() {
    var polygon = this._shape;
    for (var i = 0, len = polygon._latlngs.length; i < len; i++) {
      // update marker
      var marker = this._resizeMarkers[i];
      marker.setLatLng(polygon._latlngs[i]);

      // this one's needed to update the path
      marker._origLatLng = polygon._latlngs[i];
      if (marker._middleLeft) {
        marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
      }
      if (marker._middleRight) {
        marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
      }
    }
    // this._moveMarker.setLatLng(polygon.getBounds().getCenter());

    // show vertices
    this._shape._map.addLayer(this._markerGroup);
    this._updateMoveMarker();

    this._repositionCornerMarkers();
    this._fireEdit();
  }
228015
function init() {
  var myOptions = {
    zoom: 15,
    center: new google.maps.LatLng(61.18, -149.86),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    draggableCursor: 'default'
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  svc = new gmaps.ags.GeometryService('http://sampleserver1.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer');
  
  google.maps.event.addListener(map, 'click', function(evt) {
    projectTo(evt.latLng);
  });
  
  iw = new google.maps.InfoWindow({
    maxWidth: 200,
    content: 'Click map to project the clicked point to Alaska Albers Feet Projection',
    position: map.getCenter()
  });
  iw.open(map);
}
1073152
function(pixel, drawing) {
        if(!this.line) {
            this.createFeature(pixel);
        }
        var lonlat = this.layer.getLonLatFromViewPortPx(pixel); 
        this.point.geometry.x = lonlat.lon;
        this.point.geometry.y = lonlat.lat;
        this.callback("modify", [this.point.geometry, this.getSketch(), drawing]);
        this.point.geometry.clearBounds();
        this.drawFeature();
    }
153301
def convertPixelXYToLngLat(self, pixelX, pixelY, level):
        '''
        
        '''
        mapSize = self.getMapDimensionsByZoomLevel(level)
        x = (self.clipValue(pixelX, 0, mapSize - 1) / mapSize) - 0.5
        y = 0.5 - (self.clipValue(pixelY, 0, mapSize - 1) / mapSize)

        lat = 90 - 360 * math.atan(math.exp(-y * 2 * math.pi)) / math.pi
        lng = 360 * x

        return (lng, lat)
986256
function() {

		// Create Dom element
		this._el.content_item   = TL.Dom.create("div", "tl-media-item tl-media-map tl-media-shadow", this._el.content);

		// Get Media ID
		this.media_id = this.data.url;

		// API Call
		this.mapframe = TL.Dom.create("iframe", "", this._el.content_item);
		window.stash = this;
		this.mapframe.width       = "100%";
		this.mapframe.height      = "100%";
		this.mapframe.frameBorder = "0";
		this.mapframe.src         = this.makeGoogleMapsEmbedURL(this.media_id, this.options.api_key_googlemaps);
		
		
		// After Loaded
		this.onLoaded();
	}
852119
function(ll, map) {
    var pointC = map.latLngToContainerPoint(ll); // convert to containerpoint (pixels)
    var pointX = [pointC.x + 1, pointC.y]; // add one pixel to x

    // convert containerpoints to latlng's
    var latLngC = map.containerPointToLatLng(pointC);
    var latLngX = map.containerPointToLatLng(pointX);

    var distanceX = latLngC.distanceTo(latLngX); // calculate distance between c and x (latitude)
    return distanceX;
  }
569879
function(name, options) {
        options = options || {};
        if(!options.version) {
            options.version = typeof GMap2 === "function" ? "2" : "3";
        }
        var mixin = OpenLayers.Layer.Google["v" +
            options.version.replace(/\./g, "_")];
        if (mixin) {
            OpenLayers.Util.applyDefaults(options, mixin);
        } else {
            throw "Unsupported Google Maps API version: " + options.version;
        }

        OpenLayers.Util.applyDefaults(options, mixin.DEFAULTS);
        if (options.maxExtent) {
            options.maxExtent = options.maxExtent.clone();
        }

        OpenLayers.Layer.EventPane.prototype.initialize.apply(this,
            [name, options]);
        OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this, 
            [name, options]);

        if (this.sphericalMercator) {
            OpenLayers.Util.extend(this, OpenLayers.Layer.SphericalMercator);
            this.initMercatorParameters();
        }    
    }
356397
function(layerModel, leafletMap) {
    var self = this;

    _.bindAll(this, 'featureOut', 'featureOver', 'featureClick');

    var opts = _.clone(layerModel.attributes);

    opts.map =  leafletMap;

    var // preserve the user's callbacks
    _featureOver  = opts.featureOver,
    _featureOut   = opts.featureOut,
    _featureClick = opts.featureClick;

    opts.featureOver  = function() {
      _featureOver  && _featureOver.apply(this, arguments);
      self.featureOver  && self.featureOver.apply(this, arguments);
    };

    opts.featureOut  = function() {
      _featureOut  && _featureOut.apply(this, arguments);
      self.featureOut  && self.featureOut.apply(this, arguments);
    };

    opts.featureClick  = function() {
      _featureClick  && _featureClick.apply(this, arguments);
      self.featureClick  && self.featureClick.apply(opts, arguments);
    };

    layerModel.bind('change:visible', function() {
      self.model.get('visible') ? self.show(): self.hide();
    }, this);

    L.CartoDBLayer.prototype.initialize.call(this, opts);
    cdb.geo.LeafLetLayerView.call(this, layerModel, this, leafletMap);

  }
821426
function callpoint(error, markers) {
  markers = _.isArray(markers) ? markers : []

  var stack = error ? error.stack : null
  var out = ''

  if (stack) {
    var lines = stack.split('\n')
    var done = false
    var i

    line_loop: for (i = 1; i < lines.length; i++) {
      var line = lines[i]

      var found = false
      for (var j = 0; j < markers.length; j++) {
        if (_.isString(markers[j])) {
          found = -1 != line.indexOf(markers[j])
          if (found) break
        }
      }

      if (!found) break line_loop
    }

    out = _.isString(lines[i]) ? lines[i].substring(4) : out
  }

  return out
}
746318
def geo_map(h2, map=None, tiles='stamenterrain', cmap="wk", alpha=0.5, lw=1, fit_bounds=None, layer_name=None):
    
    if not map:
        latitude = h2.get_bin_centers(0).mean()
        longitude = h2.get_bin_centers(1).mean()
        zoom_start = 10
        map = folium.Map(location=[latitude, longitude], tiles=tiles)
        if fit_bounds == None:
            fit_bounds = True

    geo_json = _bins_to_json(h2)

    if not layer_name:
        layer_name = h2.name

    from branca.colormap import LinearColormap

    color_map = LinearColormap(cmap, vmin=h2.frequencies.min(), vmax=h2.frequencies.max())

    # legend = folium.Html("<div>Legend</div>")
    # legend_div = folium.Div("20%", "20%", "75%", "5%")
    #
    # legend_div.add_to(map)
    # legend_div.add_child(legend)

    #xx = h2.frequencies.max()

    def styling_function(bin):
        count = bin["properties"]["count"]
        return {
            "fillColor": color_map(count),
            "color": "black",
            "fillOpacity": alpha if count > 0 else 0,
            "weight": lw,
            # "strokeWidth": lw,
            "opacity": alpha if count > 0 else 0,
        }# .update(styling)

    layer = folium.GeoJson(geo_json, style_function=styling_function, name=layer_name)
    layer.add_to(map)
    if fit_bounds:
        map.fit_bounds(layer.get_bounds())
    return map
705584
function _getNeighborPixels(coord, imgSize, imgCols) {
    var res = [], pos;

    if (coord.x > 0 && coord.y > 0) { // tlPx
        pos = {
            x: coord.x - 1,
            y: coord.y - 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.y > 0) { // tPx
        pos = {
            x: coord.x,
            y: coord.y - 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.x < imgSize.w && coord.y > 0) { // trPx
        pos = {
            x: coord.x + 1,
            y: coord.y - 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.x < imgSize.w) { // rPx
        pos = {
            x: coord.x + 1,
            y: coord.y
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.x < imgSize.w && coord.y < imgSize.h) { // brPx
        pos = {
            x: coord.x + 1,
            y: coord.y + 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.y < imgSize.h) { // bPx
        pos = {
            x: coord.x,
            y: coord.y + 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.x > 0 && coord.y < imgSize.h) { // blPx
        pos = {
            x: coord.x - 1,
            y: coord.y + 1
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    if (coord.x > 0) { // lPx
        pos = {
            x: coord.x - 1,
            y: coord.y
        };
        res.push({
            coord: pos,
            color: _getColorByXY(pos, imgSize, imgCols)
        });
    }

    return res;
}
1250026
function(marker) {
        var px = this.map.getLayerPxFromLonLat(marker.lonlat);
        if (px == null) {
            marker.display(false);
        } else {
            if (!marker.isDrawn()) {
                var markerImg = marker.draw(px);
                this.div.appendChild(markerImg);
            } else if(marker.icon) {
                marker.icon.moveTo(px);
            }
        }
    }