Rectangle 27 116

If you are coming from the MySQL world, MongoDB is going to "feel" a lot more natural to you because of its query-like language support.

I think that is what makes it so friendly for a lot of people.

CouchDB is fantastic if you want to utilize the really great master-master replication support with a multi-node setup, possibly in different data centers or something like that.

MongoDB's replication (replica sets) is a master-slave-slave-slave-* setup, you can only write to the master in a replica set and read from any of them.

But if you are trying to create a global service like a CDN that needs to keep all global nodes synced even though read/write to all of them, something like the replication in CouchDB is going to be a huge boon to you.

While MongoDB has a query-like language that you can use and feels very intuitive, CouchDB takes a "map-reduce" approach and this concepts of views. It feels odd at first, but as you get the hang of it, it really starts feeling intuitive.

  • CouchDB stores all your data in a b-tree
  • You cannot "query" it dynamically with something like "SELECT * FROM user WHERE..."
  • Instead, you define discrete "views" of your data... "here is a view of all my users", "here is a view of all users older than 10" "here is a view of all users older than 30" and so on.
  • These views are defined using map-reduce approach and are defined as JavaScript functions.
  • When you define a view, the DB starts feeding all the documents of the DB you assigned the view to, through it and recording the results of your functions as the "index" on that data.
  • There are some basic queries you can do on the views like asking for a specific key (ID) or range of IDs regardless of what your map/reduce function does.
  • Read through these slides, it's the best clarification of map/reduce in Couch I've seen.

So both of these sources use JSON documents, but CouchDB follows this more "every server is a master and can sync with the world" approach which is fantastic if you need it, while MongoDB is really the MySQL of the NoSQL world.

So if that sounds more like what you need/want, go for that.

Little differences like Mongo's binary protocol vs the RESTful interface of CouchDB are all minor details.

If you want raw speed and to hell with data safety, you can make Mongo run faster than CouchDB as you can tell it to operate out of memory and not commit things to disk except for sparse intervals.

You can do the same with Couch, but it's HTTP-based communication protocol is going to be 2-4x slower than raw binary communication with Mongo in this "speed over everything!" scenario.

Keep in mind that raw crazy insane speed is useless if a server crash or disk failure corrupts and toasts your DB into oblivion, so that data point isn't as amazing as it might seem (unless you are doing real-time trading systems on Wall Street, in which case look at Redis).

"MongoDB is really the MySQL of the NoSQL world" - I don't know if things have changed but this article of 2014 disagrees: sarahmei.com/blog/2013/11/11/why-you-should-never-use-mongodb

While, loosely in spirit I think the comment still works, you are right, MUCH has changed in the last half decade and my comment should be easily dismissed.

NoSQL - MongoDB vs CouchDB - Stack Overflow

mongodb couchdb nosql
Rectangle 27 116

If you are coming from the MySQL world, MongoDB is going to "feel" a lot more natural to you because of its query-like language support.

I think that is what makes it so friendly for a lot of people.

CouchDB is fantastic if you want to utilize the really great master-master replication support with a multi-node setup, possibly in different data centers or something like that.

MongoDB's replication (replica sets) is a master-slave-slave-slave-* setup, you can only write to the master in a replica set and read from any of them.

But if you are trying to create a global service like a CDN that needs to keep all global nodes synced even though read/write to all of them, something like the replication in CouchDB is going to be a huge boon to you.

While MongoDB has a query-like language that you can use and feels very intuitive, CouchDB takes a "map-reduce" approach and this concepts of views. It feels odd at first, but as you get the hang of it, it really starts feeling intuitive.

  • CouchDB stores all your data in a b-tree
  • You cannot "query" it dynamically with something like "SELECT * FROM user WHERE..."
  • Instead, you define discrete "views" of your data... "here is a view of all my users", "here is a view of all users older than 10" "here is a view of all users older than 30" and so on.
  • These views are defined using map-reduce approach and are defined as JavaScript functions.
  • When you define a view, the DB starts feeding all the documents of the DB you assigned the view to, through it and recording the results of your functions as the "index" on that data.
  • There are some basic queries you can do on the views like asking for a specific key (ID) or range of IDs regardless of what your map/reduce function does.
  • Read through these slides, it's the best clarification of map/reduce in Couch I've seen.

So both of these sources use JSON documents, but CouchDB follows this more "every server is a master and can sync with the world" approach which is fantastic if you need it, while MongoDB is really the MySQL of the NoSQL world.

So if that sounds more like what you need/want, go for that.

Little differences like Mongo's binary protocol vs the RESTful interface of CouchDB are all minor details.

If you want raw speed and to hell with data safety, you can make Mongo run faster than CouchDB as you can tell it to operate out of memory and not commit things to disk except for sparse intervals.

You can do the same with Couch, but it's HTTP-based communication protocol is going to be 2-4x slower than raw binary communication with Mongo in this "speed over everything!" scenario.

Keep in mind that raw crazy insane speed is useless if a server crash or disk failure corrupts and toasts your DB into oblivion, so that data point isn't as amazing as it might seem (unless you are doing real-time trading systems on Wall Street, in which case look at Redis).

"MongoDB is really the MySQL of the NoSQL world" - I don't know if things have changed but this article of 2014 disagrees: sarahmei.com/blog/2013/11/11/why-you-should-never-use-mongodb

While, loosely in spirit I think the comment still works, you are right, MUCH has changed in the last half decade and my comment should be easily dismissed.

NoSQL - MongoDB vs CouchDB - Stack Overflow

mongodb couchdb nosql
Rectangle 27 2

I've found iOS 4.2 does not support window.orientation property in UIWebView, while in mobile safari it works... So, the only way I have found in order to make my JS react to orientation changes was to make my objective-c code call a javascript function defined in currently displayed UIWebView webpage. Here's a sample code, overriding ViewController's didRotateFromInterfaceOrientation method:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    [webView stringByEvaluatingJavaScriptFromString:
          [NSString stringWithFormat:@"didRotateTo('%@')", 
            [self currentOrientationAsString]]];
}
- (NSString*) currentOrientationAsString {
    switch([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationLandscapeLeft:
        case UIDeviceOrientationLandscapeRight:
            return @"landscape";
    }
    return @"portrait"; // assuming portrait is default
}

You have to define your Javascript function as follows:

function didRotateTo(ori) {
  if (ori=="portrait") {
    // ... do something
  } else {
    // ... do something else
  }
}

I seem to discover the same problem, as the solution by Martijn Th doesn't call my function. Is it somehow possible to "call" the event onorientationchange?

iPhone UIWebView local resources using Javascript and handling onorien...

uiwebview iphone
Rectangle 27 12

I've had success with a solution with overriding __doPostBack() so as to call an override on form.submit() (i.e. $('form:first').submit(myHandler)), but I think it's over-engineered. As of ASP.NET 2.0, the most simple workaround is to:

Define a javascript function that you want to run when the form is submitted i.e.

<script type="text/javascript">

function myhandler()
{
    alert('you submitted!');
}

</script>
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(), 
                                            "myHandlerKey", "myhandler()");
}

That's all! myhandler() will be called from straightforward button-input submits and automatic __doPostBack() calls alike.

Just to clarify, in your example "myHandlerKey" is the id of the form tag. Like this: <form id="myHandlerKey" runat="server">

Sorry, no - check the documentation: msdn.microsoft.com/en-us/library/bb301794.aspx. The key uniquely identifies the script to help prevent duplicate registration. Incidentally there should be no need to uniquely identify a form element as webforms only allow one form per page.

To clarify: webforms only allow one form per page declared with runat="server". You may have other non-server forms on the page.

I like this. It's the proper ".NET way" of handling things.

How to capture submit event using jQuery in an ASP.NET application? - ...

asp.net jquery webforms form-submit
Rectangle 27 12

I've had success with a solution with overriding __doPostBack() so as to call an override on form.submit() (i.e. $('form:first').submit(myHandler)), but I think it's over-engineered. As of ASP.NET 2.0, the most simple workaround is to:

Define a javascript function that you want to run when the form is submitted i.e.

<script type="text/javascript">

function myhandler()
{
    alert('you submitted!');
}

</script>
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(), 
                                            "myHandlerKey", "myhandler()");
}

That's all! myhandler() will be called from straightforward button-input submits and automatic __doPostBack() calls alike.

Just to clarify, in your example "myHandlerKey" is the id of the form tag. Like this: <form id="myHandlerKey" runat="server">

Sorry, no - check the documentation: msdn.microsoft.com/en-us/library/bb301794.aspx. The key uniquely identifies the script to help prevent duplicate registration. Incidentally there should be no need to uniquely identify a form element as webforms only allow one form per page.

To clarify: webforms only allow one form per page declared with runat="server". You may have other non-server forms on the page.

I like this. It's the proper ".NET way" of handling things.

How to capture submit event using jQuery in an ASP.NET application? - ...

asp.net jquery webforms form-submit
Rectangle 27 1

The problem was that when I define the javascript function, it became like static, it means, It just execute once and the variable finalized gets the defined values when the page loads. So, when I clicked the button it retrieve the value predefined, no te value at that moment. But if I refresh the page, the variable gets the value at the moment of the refresh.

So to solve this, I just put my javascript code directly in the oncomplete method and finally WORKS :D

Maybe a better solution could be to find a way to refresh the javascript code each time the button is clicked, because if I put the javascript code in the oncomplete method, it seems dirty, because of the lot of characters in a line.

javascript - oncomplete method doesn't always executes after action, J...

javascript jsf richfaces
Rectangle 27 2

Probably too late, but I recently had to deal with google maps in vb and wanted to share my solution:

The first part of this example explains how to implement it. In the second, I will explain how it works. This tries to be a general example. The template for the map (see step 3) and the example functions are fully customizable.

Step 1. Firstly, create a new project and select Windows Form Application. Let's leave its name as "Form1".

Step 3. Create a .html file named "googlemap_template.html" with your favourite text editor and paste the following code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
     <style type="text/css">
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #gmap {
        height: 100%;
      }
     </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        function initialize() {
            //Use window.X instead of var X to make a variable globally available 
            window.markers = new Array();
            window.marker_data = [[MARKER_DATA]];
            window.gmap = new google.maps.Map(document.getElementById('gmap'), {
            zoom: 15,
            center: new google.maps.LatLng(marker_data[0][0], marker_data[0][1]),
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
          var infowindow = new google.maps.InfoWindow();
          var newmarker, i;
          for (i = 0; i < marker_data.length; i++) {
              if (marker_data[0].length == 2) {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap
                  });
              } else if (marker_data[0].length == 3) {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap,
                      title: (marker_data[i][2])
                  });
              } else {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap,
                      title: (marker_data[i][2]),
                      icon: (marker_data[i][3])
                  });
              }
            google.maps.event.addListener(newmarker, 'click', (function (newmarker, i) {
                return function () {
                    if (newmarker.title) {
                        infowindow.setContent(newmarker.title);
                        infowindow.open(gmap, newmarker);
                    }
                    gmap.setCenter(newmarker.getPosition());
                    // Calling functions written in the WF
                    window.external.showVbHelloWorld();
                    window.external.getMarkerDataFromJavascript(newmarker.title,i);
                }
            })(newmarker, i));
            markers[i] = newmarker;
          }
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <script type="text/javascript">
        // Function triggered from the WF with no arguments
        function showJavascriptHelloWorld() {
            alert("Hello world in HTML from WF");
        }
     </script>
      <script type="text/javascript">
        // Function triggered from the WF with a String argument
        function focusMarkerFromIdx(idx) {
            google.maps.event.trigger(markers[idx], 'click');
        }
      </script>
  </head>
  <body>
    <div id="gmap"></div>
  </body>
</html>

Step 5. Once it appears in your Solution Explorer, set its properties to: - Build Action -> Embedded Resource - Custom Tool Namespace -> write the name of the project

Step 6. Add a new class (right click on your project->add->class). In my example I'll call it GoogleMapHelper.

Step 7. Paste the following code into your class:

Imports System.IO
    Imports System.Reflection
    Imports System.Text

    Public Class GoogleMapHelper

    ' 1- googlemap_template.html must be copied in the main project folder
    ' 2- add the file into the Visual Studio Solution Explorer (add existing file)
    ' 3- set the properties of the file to: 
    '                                   Build Action -> Embedded Resource
    '                                   Custom Tool Namespace -> write the name of the project

    Private Const ICON_FOLDER As String = "marker_icons/" 'images must be stored in a folder inside  Debug/Release folder
    Private Const MAP_TEMPLATE As String = "WindowsApplication1.googlemap_template.html"
    Private Const TEXT_TO_REPLACE_MARKER_DATA As String = "[[MARKER_DATA]]"
    Private Const TMP_NAME As String = "tmp_map.html"


    Private mWebBrowser As WebBrowser

    'MARKER POSITIONS 
    Private mPositions As Double(,) 'lat, lon
    ' marker data allows different formats to include lat,long and optionally title and icon:
    ' op1: mMarkerData = New String(N-1, 1) {{lat1, lon1}, {lat2, lon2}, {latN, lonN}} 
    ' op2: mMarkerData = New String(N-1, 2) {{lat1, lon1,'title1'}, {lat2, lon2,'title2'}, {latN, lonN, 'titleN'}} 
    ' op3: mMarkerData = New String(N-1, 3) {{lat1, lon1,'title1','image1.png'}, {lat2, lon2,'title2','image2.png'}, {latN, lonN, 'titleN','imageN.png'}} 
    Private mMarkerData As String(,) = Nothing


    Public Sub New(ByRef wb As WebBrowser, pos As Double(,))
        mWebBrowser = wb
        mPositions = pos
        mMarkerData = getMarkerDataFromPositions(pos)
    End Sub

    Public Sub New(ByRef wb As WebBrowser, md As String(,))
        mWebBrowser = wb
        mMarkerData = md
    End Sub

    Public Sub loadMap()
        mWebBrowser.Navigate(getMapTemplate())
    End Sub

    Private Function getMapTemplate() As String

        If mMarkerData Is Nothing Or mMarkerData.GetLength(1) > 4 Then
            MessageBox.Show("Marker data has not the proper size. It must have 2, 3 o 4 columns")
            Return Nothing
        End If

        Dim htmlTemplate As New StringBuilder()
        Dim tmpFolder As String = Environment.GetEnvironmentVariable("TEMP")
        Dim dataSize As Integer = mMarkerData.GetLength(1) 'number of columns
        Dim mMarkerDataAsText As String = String.Empty
        Dim myresourcePath As String = My.Resources.ResourceManager.BaseName
        Dim myresourcefullPath As String = Path.GetFullPath(My.Resources.ResourceManager.BaseName)
        Dim localPath = myresourcefullPath.Replace(myresourcePath, "").Replace("\", "/") & ICON_FOLDER

        htmlTemplate.AppendLine(getStringFromResources(MAP_TEMPLATE))
        mMarkerDataAsText = "["

        For i As Integer = 0 To mMarkerData.GetLength(0) - 1
            If i <> 0 Then
                mMarkerDataAsText += ","
            End If
            If dataSize = 2 Then 'lat,lon
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & "]"
            ElseIf dataSize = 3 Then 'lat,lon and title
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & ",'" & mMarkerData(i, 2) & "']"
            ElseIf dataSize = 4 Then 'lat,lon,title and image
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & ",'" & mMarkerData(i, 2) & "','" & localPath & mMarkerData(i, 3) & "']" 'Ojo a las comillas simples en las columnas 3 y 4 
            End If
        Next

        mMarkerDataAsText += "]"
        htmlTemplate.Replace(TEXT_TO_REPLACE_MARKER_DATA, mMarkerDataAsText)

        Dim tmpHtmlMapFile As String = (tmpFolder & Convert.ToString("\")) + TMP_NAME
        Dim existsMapFile As Boolean = False
        Try
            existsMapFile = createTxtFile(tmpHtmlMapFile, htmlTemplate)
        Catch ex As Exception
            MessageBox.Show("Error writing temporal file", "Writing Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
        End Try

        If existsMapFile Then
            Return tmpHtmlMapFile
        Else
            Return Nothing
        End If
    End Function

    Private Function getMarkerDataFromPositions(pos As Double(,)) As String(,)
        Dim md As String(,) = New String(pos.GetLength(0) - 1, 1) {}
        For i As Integer = 0 To pos.GetLength(0) - 1
            md(i, 0) = pos(i, 0).ToString("g", New System.Globalization.CultureInfo("en-US"))
            md(i, 1) = pos(i, 1).ToString("g", New System.Globalization.CultureInfo("en-US"))
        Next
        Return md
    End Function

    Private Function getStringFromResources(resourceName As String) As String
        Dim assem As Assembly = Me.[GetType]().Assembly

        Using stream As Stream = assem.GetManifestResourceStream(resourceName)
            Try
                Using reader As New StreamReader(stream)
                    Return reader.ReadToEnd()
                End Using
            Catch e As Exception
                Throw New Exception((Convert.ToString("Error de acceso al Recurso '") & resourceName) + "'" & vbCr & vbLf + e.ToString())
            End Try
        End Using
    End Function

    Private Function createTxtFile(mFile As String, content As StringBuilder) As Boolean
        Dim mPath As String = Path.GetDirectoryName(mFile)
        If Not Directory.Exists(mPath) Then
            Directory.CreateDirectory(mPath)
        End If
        If File.Exists(mFile) Then
            File.Delete(mFile)
        End If
        Dim sw As StreamWriter = File.CreateText(mFile)
        sw.Write(content.ToString())
        sw.Close()
        Return True
    End Function
    End Class

Note: The MAP_TEMPLATE constant must include the name of your project

Step 8. Now we can use our GoogleMapHelper class to load the map into our webbrowser by simply creating and instance and calling its loadMap() method. How you build your markerData is up to you. In this example, for clarification, I write them by hand. There are 3 options to define the marker data (see GoogleMapHelper class comments). Note that if you use the third option (including title and icons) you must create a folder called "marker_icons" (or whatever you define in the GoogleMapHelper constant ICON_FOLDER) in your Debug/Release folder and place there your .png files. In my case:

I created two buttons in my Form1 to illustrate how the map and the WF interact. Here is how it looks:

And here is the code:

Imports System.IO
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Text
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>
Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.wbmap.ObjectForScripting = Me

    Dim onlyPositions As Double(,) = New Double(2, 1) {{42.13557, -0.40806}, {42.13684, -0.40884}, {42.13716, -0.40729}}
    Dim positonAndTitles As String(,) = New String(2, 2) {{"42.13557", "-0.40806", "marker0"}, {"42.13684", "-0.40884", "marker1"}, {"42.13716", "-0.40729", "marker2"}}
    Dim positonTitlesAndIcons As String(,) = New String(2, 3) {{"42.13557", "-0.40806", "marker0", "truck_red.png"}, {"42.13684", "-0.40884", "marker1", "truck_red.png"}, {"42.13716", "-0.40729", "marker2", "truck_red.png"}}

    'Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, onlyPositions)
    'Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, positonAndTitles)
    Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, positonTitlesAndIcons)
    gmh.loadMap()
End Sub

'############################### CALLING JAVASCRIPT METHODS ##############################
'This methods call methods written in googlemap_template.html
Private Sub callMapJavascript(sender As Object, e As EventArgs) Handles Button1.Click
    wbmap.Document.InvokeScript("showJavascriptHelloWorld")
End Sub

Private Sub callMapJavascriptWithArguments(sender As Object, e As EventArgs) Handles Button2.Click
    wbmap.Document.InvokeScript("focusMarkerFromIdx", New String() {2})
End Sub
'#########################################################################################

'############################### METHODS CALLED FROM JAVASCRIPT ##########################
'This methods are called by the javascript defined in googlemap_template.html when some events are triggered
Public Sub getMarkerDataFromJavascript(title As String, idx As String)
    MsgBox("Title: " & title & " idx: " & idx)
End Sub

Public Sub showVbHelloWorld()
    MsgBox("Hello world in WF from HTML")
End Sub
End Class
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>

What they do is to tell the .NET Framework that we want fulltrust and make the class visible to COM so Form1 is visible to JavaScript.

Also don't forget this in your Form1 load function:

Me.wbmap.ObjectForScripting = Me

It exposes your Form1 class to the JavaScript on the googlemap_template.hmtl page.

Now you can execute and it should be working

Basically, what our GoogleMapHelper class does is to read our googlemap_template.html, make a temporal copy, replace the code related to the markers ([[MARKER_DATA]]) and execute the page in the web browser control of our form. This html loops through all the markers and assigns a 'click' listener to each one. This click function is obviously fully customizable. In the example it opens an infowindow if the marker has a title, centers the map in such marker and calls two external functions that are defined in our Form1 class.

On the other hand, we can define other javascript functions (with or without arguments) in this html to be called from our Windows Form (by using wbmap.Document.InvokeScript).

Outstanding work here. I'm about to undergo a similar project. Hoping I can refer to this for guidance. I need an interface (w/menu) and a display that allows the user to click around the map to create a path (using this API): developers.google.com/maps/documentation/javascript/examples/. I THEN need a way to export their selection(s) to a KML file... Should be a blast... : /

glad you like it! it should indeed guide you. I haven't used polylines, but in any case they are just a list of marker positions, so you should not have problems to retrieve their lat,lon coordinates and call a function in your WF to export your file. Good luck!

vb.net - Adding Google Maps to a VB 2010 application - Stack Overflow

vb.net winforms google-maps
Rectangle 27 2

Probably too late, but I recently had to deal with google maps in vb and wanted to share my solution:

The first part of this example explains how to implement it. In the second, I will explain how it works. This tries to be a general example. The template for the map (see step 3) and the example functions are fully customizable.

Step 1. Firstly, create a new project and select Windows Form Application. Let's leave its name as "Form1".

Step 3. Create a .html file named "googlemap_template.html" with your favourite text editor and paste the following code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
     <style type="text/css">
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #gmap {
        height: 100%;
      }
     </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        function initialize() {
            //Use window.X instead of var X to make a variable globally available 
            window.markers = new Array();
            window.marker_data = [[MARKER_DATA]];
            window.gmap = new google.maps.Map(document.getElementById('gmap'), {
            zoom: 15,
            center: new google.maps.LatLng(marker_data[0][0], marker_data[0][1]),
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
          var infowindow = new google.maps.InfoWindow();
          var newmarker, i;
          for (i = 0; i < marker_data.length; i++) {
              if (marker_data[0].length == 2) {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap
                  });
              } else if (marker_data[0].length == 3) {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap,
                      title: (marker_data[i][2])
                  });
              } else {
                  newmarker = new google.maps.Marker({
                      position: new google.maps.LatLng(marker_data[i][0], marker_data[i][1]),
                      map: gmap,
                      title: (marker_data[i][2]),
                      icon: (marker_data[i][3])
                  });
              }
            google.maps.event.addListener(newmarker, 'click', (function (newmarker, i) {
                return function () {
                    if (newmarker.title) {
                        infowindow.setContent(newmarker.title);
                        infowindow.open(gmap, newmarker);
                    }
                    gmap.setCenter(newmarker.getPosition());
                    // Calling functions written in the WF
                    window.external.showVbHelloWorld();
                    window.external.getMarkerDataFromJavascript(newmarker.title,i);
                }
            })(newmarker, i));
            markers[i] = newmarker;
          }
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <script type="text/javascript">
        // Function triggered from the WF with no arguments
        function showJavascriptHelloWorld() {
            alert("Hello world in HTML from WF");
        }
     </script>
      <script type="text/javascript">
        // Function triggered from the WF with a String argument
        function focusMarkerFromIdx(idx) {
            google.maps.event.trigger(markers[idx], 'click');
        }
      </script>
  </head>
  <body>
    <div id="gmap"></div>
  </body>
</html>

Step 5. Once it appears in your Solution Explorer, set its properties to: - Build Action -> Embedded Resource - Custom Tool Namespace -> write the name of the project

Step 6. Add a new class (right click on your project->add->class). In my example I'll call it GoogleMapHelper.

Step 7. Paste the following code into your class:

Imports System.IO
    Imports System.Reflection
    Imports System.Text

    Public Class GoogleMapHelper

    ' 1- googlemap_template.html must be copied in the main project folder
    ' 2- add the file into the Visual Studio Solution Explorer (add existing file)
    ' 3- set the properties of the file to: 
    '                                   Build Action -> Embedded Resource
    '                                   Custom Tool Namespace -> write the name of the project

    Private Const ICON_FOLDER As String = "marker_icons/" 'images must be stored in a folder inside  Debug/Release folder
    Private Const MAP_TEMPLATE As String = "WindowsApplication1.googlemap_template.html"
    Private Const TEXT_TO_REPLACE_MARKER_DATA As String = "[[MARKER_DATA]]"
    Private Const TMP_NAME As String = "tmp_map.html"


    Private mWebBrowser As WebBrowser

    'MARKER POSITIONS 
    Private mPositions As Double(,) 'lat, lon
    ' marker data allows different formats to include lat,long and optionally title and icon:
    ' op1: mMarkerData = New String(N-1, 1) {{lat1, lon1}, {lat2, lon2}, {latN, lonN}} 
    ' op2: mMarkerData = New String(N-1, 2) {{lat1, lon1,'title1'}, {lat2, lon2,'title2'}, {latN, lonN, 'titleN'}} 
    ' op3: mMarkerData = New String(N-1, 3) {{lat1, lon1,'title1','image1.png'}, {lat2, lon2,'title2','image2.png'}, {latN, lonN, 'titleN','imageN.png'}} 
    Private mMarkerData As String(,) = Nothing


    Public Sub New(ByRef wb As WebBrowser, pos As Double(,))
        mWebBrowser = wb
        mPositions = pos
        mMarkerData = getMarkerDataFromPositions(pos)
    End Sub

    Public Sub New(ByRef wb As WebBrowser, md As String(,))
        mWebBrowser = wb
        mMarkerData = md
    End Sub

    Public Sub loadMap()
        mWebBrowser.Navigate(getMapTemplate())
    End Sub

    Private Function getMapTemplate() As String

        If mMarkerData Is Nothing Or mMarkerData.GetLength(1) > 4 Then
            MessageBox.Show("Marker data has not the proper size. It must have 2, 3 o 4 columns")
            Return Nothing
        End If

        Dim htmlTemplate As New StringBuilder()
        Dim tmpFolder As String = Environment.GetEnvironmentVariable("TEMP")
        Dim dataSize As Integer = mMarkerData.GetLength(1) 'number of columns
        Dim mMarkerDataAsText As String = String.Empty
        Dim myresourcePath As String = My.Resources.ResourceManager.BaseName
        Dim myresourcefullPath As String = Path.GetFullPath(My.Resources.ResourceManager.BaseName)
        Dim localPath = myresourcefullPath.Replace(myresourcePath, "").Replace("\", "/") & ICON_FOLDER

        htmlTemplate.AppendLine(getStringFromResources(MAP_TEMPLATE))
        mMarkerDataAsText = "["

        For i As Integer = 0 To mMarkerData.GetLength(0) - 1
            If i <> 0 Then
                mMarkerDataAsText += ","
            End If
            If dataSize = 2 Then 'lat,lon
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & "]"
            ElseIf dataSize = 3 Then 'lat,lon and title
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & ",'" & mMarkerData(i, 2) & "']"
            ElseIf dataSize = 4 Then 'lat,lon,title and image
                mMarkerDataAsText += "[" & mMarkerData(i, 0) & "," + mMarkerData(i, 1) & ",'" & mMarkerData(i, 2) & "','" & localPath & mMarkerData(i, 3) & "']" 'Ojo a las comillas simples en las columnas 3 y 4 
            End If
        Next

        mMarkerDataAsText += "]"
        htmlTemplate.Replace(TEXT_TO_REPLACE_MARKER_DATA, mMarkerDataAsText)

        Dim tmpHtmlMapFile As String = (tmpFolder & Convert.ToString("\")) + TMP_NAME
        Dim existsMapFile As Boolean = False
        Try
            existsMapFile = createTxtFile(tmpHtmlMapFile, htmlTemplate)
        Catch ex As Exception
            MessageBox.Show("Error writing temporal file", "Writing Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
        End Try

        If existsMapFile Then
            Return tmpHtmlMapFile
        Else
            Return Nothing
        End If
    End Function

    Private Function getMarkerDataFromPositions(pos As Double(,)) As String(,)
        Dim md As String(,) = New String(pos.GetLength(0) - 1, 1) {}
        For i As Integer = 0 To pos.GetLength(0) - 1
            md(i, 0) = pos(i, 0).ToString("g", New System.Globalization.CultureInfo("en-US"))
            md(i, 1) = pos(i, 1).ToString("g", New System.Globalization.CultureInfo("en-US"))
        Next
        Return md
    End Function

    Private Function getStringFromResources(resourceName As String) As String
        Dim assem As Assembly = Me.[GetType]().Assembly

        Using stream As Stream = assem.GetManifestResourceStream(resourceName)
            Try
                Using reader As New StreamReader(stream)
                    Return reader.ReadToEnd()
                End Using
            Catch e As Exception
                Throw New Exception((Convert.ToString("Error de acceso al Recurso '") & resourceName) + "'" & vbCr & vbLf + e.ToString())
            End Try
        End Using
    End Function

    Private Function createTxtFile(mFile As String, content As StringBuilder) As Boolean
        Dim mPath As String = Path.GetDirectoryName(mFile)
        If Not Directory.Exists(mPath) Then
            Directory.CreateDirectory(mPath)
        End If
        If File.Exists(mFile) Then
            File.Delete(mFile)
        End If
        Dim sw As StreamWriter = File.CreateText(mFile)
        sw.Write(content.ToString())
        sw.Close()
        Return True
    End Function
    End Class

Note: The MAP_TEMPLATE constant must include the name of your project

Step 8. Now we can use our GoogleMapHelper class to load the map into our webbrowser by simply creating and instance and calling its loadMap() method. How you build your markerData is up to you. In this example, for clarification, I write them by hand. There are 3 options to define the marker data (see GoogleMapHelper class comments). Note that if you use the third option (including title and icons) you must create a folder called "marker_icons" (or whatever you define in the GoogleMapHelper constant ICON_FOLDER) in your Debug/Release folder and place there your .png files. In my case:

I created two buttons in my Form1 to illustrate how the map and the WF interact. Here is how it looks:

And here is the code:

Imports System.IO
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Text
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>
Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.wbmap.ObjectForScripting = Me

    Dim onlyPositions As Double(,) = New Double(2, 1) {{42.13557, -0.40806}, {42.13684, -0.40884}, {42.13716, -0.40729}}
    Dim positonAndTitles As String(,) = New String(2, 2) {{"42.13557", "-0.40806", "marker0"}, {"42.13684", "-0.40884", "marker1"}, {"42.13716", "-0.40729", "marker2"}}
    Dim positonTitlesAndIcons As String(,) = New String(2, 3) {{"42.13557", "-0.40806", "marker0", "truck_red.png"}, {"42.13684", "-0.40884", "marker1", "truck_red.png"}, {"42.13716", "-0.40729", "marker2", "truck_red.png"}}

    'Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, onlyPositions)
    'Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, positonAndTitles)
    Dim gmh As GoogleMapHelper = New GoogleMapHelper(wbmap, positonTitlesAndIcons)
    gmh.loadMap()
End Sub

'############################### CALLING JAVASCRIPT METHODS ##############################
'This methods call methods written in googlemap_template.html
Private Sub callMapJavascript(sender As Object, e As EventArgs) Handles Button1.Click
    wbmap.Document.InvokeScript("showJavascriptHelloWorld")
End Sub

Private Sub callMapJavascriptWithArguments(sender As Object, e As EventArgs) Handles Button2.Click
    wbmap.Document.InvokeScript("focusMarkerFromIdx", New String() {2})
End Sub
'#########################################################################################

'############################### METHODS CALLED FROM JAVASCRIPT ##########################
'This methods are called by the javascript defined in googlemap_template.html when some events are triggered
Public Sub getMarkerDataFromJavascript(title As String, idx As String)
    MsgBox("Title: " & title & " idx: " & idx)
End Sub

Public Sub showVbHelloWorld()
    MsgBox("Hello world in WF from HTML")
End Sub
End Class
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>

What they do is to tell the .NET Framework that we want fulltrust and make the class visible to COM so Form1 is visible to JavaScript.

Also don't forget this in your Form1 load function:

Me.wbmap.ObjectForScripting = Me

It exposes your Form1 class to the JavaScript on the googlemap_template.hmtl page.

Now you can execute and it should be working

Basically, what our GoogleMapHelper class does is to read our googlemap_template.html, make a temporal copy, replace the code related to the markers ([[MARKER_DATA]]) and execute the page in the web browser control of our form. This html loops through all the markers and assigns a 'click' listener to each one. This click function is obviously fully customizable. In the example it opens an infowindow if the marker has a title, centers the map in such marker and calls two external functions that are defined in our Form1 class.

On the other hand, we can define other javascript functions (with or without arguments) in this html to be called from our Windows Form (by using wbmap.Document.InvokeScript).

Outstanding work here. I'm about to undergo a similar project. Hoping I can refer to this for guidance. I need an interface (w/menu) and a display that allows the user to click around the map to create a path (using this API): developers.google.com/maps/documentation/javascript/examples/. I THEN need a way to export their selection(s) to a KML file... Should be a blast... : /

glad you like it! it should indeed guide you. I haven't used polylines, but in any case they are just a list of marker positions, so you should not have problems to retrieve their lat,lon coordinates and call a function in your WF to export your file. Good luck!

vb.net - Adding Google Maps to a VB 2010 application - Stack Overflow

vb.net winforms google-maps
Rectangle 27 39

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 39

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 38

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 38

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 38

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 37

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 37

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 37

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 37

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 37

A function defines a new environment

This describes the common mistake with using closures in JavaScript.

function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.

Using a closure in a loop is tricky.

var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    }; 
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!

This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons. Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a reference to the newest object.

function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  }; 
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated new copies upon entry.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 151

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented