Deprecated: Assigning the return value of new by reference is deprecated in /home/gathadam/public_html/wp-settings.php on line 520

Deprecated: Assigning the return value of new by reference is deprecated in /home/gathadam/public_html/wp-settings.php on line 535

Deprecated: Assigning the return value of new by reference is deprecated in /home/gathadam/public_html/wp-settings.php on line 542

Deprecated: Assigning the return value of new by reference is deprecated in /home/gathadam/public_html/wp-settings.php on line 578

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/gathadam/public_html/wp-settings.php on line 18
2007 August

Draggable Marker Google Maps Demo

So you’ve been checking out my previous posts on Google Maps and Draggable Markers, and it would be nice to have a demo so you can see the draggable markers in action.

Check this out:

And the code as well? Here is the source for the Google Maps Demo

Add Draggable Markers and Events to your Google Maps

Following on from my last post on how to add Google Maps to your ASP.Net site, I’m now going to show how easy it is to add draggable markers to your map.

First, make sure you have the map working on your webform.

Having the map fire server-side events on user actions is pretty simple, and here is the code:


    Private Sub AddEventToMapDemo()
        Dim GeoCode As Subgurim.Controles.GeoCode
        Dim sMapKey As String = System.Configuration.ConfigurationManager.AppSettings("googlemaps.subgurim.net")

        GeoCode = GMap.geoCodeRequest("3052. VIC. australia", sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng)

        GMap.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oOption As New Subgurim.Controles.GMarkerOptions
        oOption.draggable = True
        oMarker = New Subgurim.Controles.GMarker(gLatLng, oOption)
        GMap.addGMarker(oMarker)

        GMap.addListener(New Subgurim.Controles.GListener(oMarker.ID, Subgurim.Controles.GListener.Event.dragend, _
        "function(){{ var ev = new serverEvent('dragend', 0); ev.addArg(" & oMarker.ID & ".getPoint().lat()); ev.addArg(" & oMarker.ID & ".getPoint().lng()); ev.send(); }}"))

    End Sub

You then need to add code to handle the event:


    Protected Function GMap_ServerEvent(ByVal s As Object, ByVal e As Subgurim.Controles.GAjaxServerEventOtherArgs) As String

        If e.eventName = "dragend" Then
            Response.Write("New Latitude =" & e.eventArgs(0) & ", New Longitude = " & e.eventArgs(1))
        End If

    End Function

The server-side event will be fired every time the marker is dragged and dropped.

In my situation, I wanted to allow the user to drag & drop the marker as many times as they wanted - and only store the new Lat/Long values when the user pressed the Save button.

This is a little bit harder to code as the variables used to reference the marker cannot be accessed globally - so we can’t just read their values when the user presses the save button (to the gurus: I’m sure they can, but I couldn’t find an easy way to get at them) . However, we can store them in hidden fields when the DragEnd event is raised, and examine those fields when Save is pressed.

Add these fields to your webform:


<input type=hidden id="hidLat" name="hidLat" runat=server />
<input type=hidden id="hidLng" name="hidLng" runat=server />
<asp:Button ID="Button1" runat="server" Text="Save" />

And add this sub to your code-behind:


    Private Sub NewLatLongOnSaveMapDemo()
        Dim GeoCode As Subgurim.Controles.GeoCode
        Dim sMapKey As String = System.Configuration.ConfigurationManager.AppSettings("googlemaps.subgurim.net")

        GeoCode = GMap.geoCodeRequest("3052. VIC. australia", sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng)

        GMap.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oOption As New Subgurim.Controles.GMarkerOptions
        oOption.draggable = True
        oMarker = New Subgurim.Controles.GMarker(gLatLng, oOption)
        GMap.addGMarker(oMarker)

            GMap.addListener(New Subgurim.Controles.GListener(oMarker.ID, Subgurim.Controles.GListener.Event.dragend, _
            "function(){ document.getElementById('hidLat').value=" & oMarker.ID & ".getPoint().lat();document.getElementById('hidLng').value=" & oMarker.ID & ".getPoint().lng() }"))

    End Sub

And here is the ‘Save’ button click event:


    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Write("New Latitude =" & hidLat.Value & ", New Longitude = " & Me.hidLng.Value)
    End Sub

Code the perfect Exit Popup (exit console)

All popups are bad news, right? Nothing gets rid of visitors faster than a crappy ad for casinoviagraporn getting in their face.

But what about visitors that found your site through a search engine, spend 5 seconds on 1 page of your site & then press the back button?

They didn’t find what they want.
They aren’t coming back.
Don’t they deserve some popup love?

Seriously, you have (most likely) lost these visitors for good anyway, so showing them a popup won’t make much difference to your visitor retention.

So how do you do it?
The key is the javascript event onUnload. This fires when a page is exited, whether by navigating out via a link, pressing the back button or closing the browser. The problem is, it fires every time a page unloads - and we only want a popup when the visitor leaves your site (not every time they navigate to a new page on your site).

Over at consolescripts.com they describe a solution which involves adding an onClick event to every internal link. The onClick event effectively blocks the popup from firing within the onUnload event.

Its a good solution, but finding every internal link within a decent sized site is a nightmare. So we need an automatic way of adding the onClick event to internal links, and it must not overwrite any existing onClick events we have already set up (unobtrusive javascript).

Check this out:


var Page_Enter;
var TimeLimit=20;
var Page_ShowPopOnExit=false;
var MySiteDomain='YOURSITE.COM';

function XBrowserAddHandlerPops(target,eventName,handlerName) {
  if ( target.addEventListener ) {
    target.addEventListener(eventName, function(e){target[handlerName](e);}, false);
  } else if ( target.attachEvent ) {
    target.attachEvent("on" + eventName, function(e){target[handlerName](e);});
  } else {
    var originalHandler = target["on" + eventName];
    if ( originalHandler ) {
      target["on" + eventName] = function(e){originalHandler(e);target[handlerName](e);};
    } else {
      target["on" + eventName] = target[handlerName];
    }
  }
}

function InternalLink() {
	Page_ShowPopOnExit = false;
}

function PageEnter() {
   Page_Enter=new Date();
}

function SiteExit() {
   var time_dif;
   var Page_Exit=new Date();
   time_dif=(Page_Exit.getTime()-Page_Enter.getTime())/1000;
   time_dif=Math.round(time_dif);
   if (time_dif<=TimeLimit && Page_ShowPopOnExit==true)
	{
	alert('Here is your popup!');
	}
}

function LinkConvert()
{
var href;
	var anchors = document.getElementsByTagName('a');

	for(var y=0; y<anchors.length; y++)
	{
		href = anchors[y].href.toLowerCase();
		if (!(href.indexOf("http://")!=-1 && href.indexOf(MySiteDomain)==-1))
			{
			anchors[y].clickhandler=InternalLink
			XBrowserAddHandlerPops(anchors[y],"click","clickhandler");
			}
	}
}

XBrowserAddHandlerPops(window,"load","PageEnter");
XBrowserAddHandlerPops(window,"load","LinkConvert");
XBrowserAddHandlerPops(window,"unload","SiteExit");
Page_ShowPopOnExit=true;

Save this as popup.js

The javascript does a few things.

  1. As soon as the page is finished loading a copy of the time is stored, so we can tell how long they have been on the page.
  2. All internal links have an onClick event handler added. An internal link is determined as one is missing ‘http://’ (internal relative links do not have the http:// ) and your domain name in the href. Note: If you are using javascript links for internal navigation then this method will not work. However, it should be easy to add the ‘Page_ShowPopOnExit = false;’ to your javascript link code.
  3. When the page unloads 2 checks are done; Has the person left the page within XX seconds? (if they stay 5 minutes then perhaps they liked your site, so no popup for them). Is the visitor following an internal link? If the answers are Yes & No respectively, then show them a pop.

Great, but if we just add this .js file to every page on our site then even people who directly type in our URL can be shown pops. These are the hardest of our hardcore fans, and should never get a pop. Also, I only want to show pops to people that hit my site from a search engine & immediately leave - if they visit more than 1 page then no pop for them.

So we need to inspect the Referrer, and check that they are coming from a search engine. I’m going to do this server side so I can cut down on my page size if the visitor is not pop-worthy.

In ASP.Net (put it in the page.load event):


Dim sPageReferrer As String = ""
If Not (Request.UrlReferrer Is Nothing) Then
    sPageReferrer = LCase(Request.UrlReferrer.ToString)
End If
If InStr(sPageReferrer, "google.com") > 0 Or InStr(sPageReferrer, "yahoo.com") > 0 Or InStr(sPageReferrer, "live.com") > 0 Then
    RegisterClientScriptBlock("PopUnder", "<script src='includes/popunder.js' type='text/javascript'></script>")
End If

If you wanted to do this in the .js file, then just change the last bit of popup.js to:


var href = document.referrer.toLowerCase();
if (href.indexOf("google.com")!=-1 || href.indexOf("yahoo.com")!=-1 || href.indexOf("live.com")!=-1)
	{
	XBrowserAddHandlerPops(window,"load","PageEnter");
	XBrowserAddHandlerPops(window,"load","LinkConvert");
	XBrowserAddHandlerPops(window,"unload","SiteExit");
	Page_ShowPopOnExit=true;
	}


Add Google Maps to your .Net site in 10 minutes

Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward.

Basically, the guys over at subgurim.net have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.

But all this is cutting into your bragging time - so lets get started!

1. Get a Google Maps API key from here:
http://www.google.com/apis/maps/

2. Download the SubGurim wrapper dll from here:
http://en.googlemaps.subgurim.net/descargar.aspx

3. Unzip it, and put it in your \bin directory

4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.

5. Add a new webpage.

6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′

7. Add the following lines to your web.config file:


  <appSettings>
    <add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />
  </appSettings>

8. Add the following code to your Page.Load sub


        Dim sStreetAddress As String
        Dim sMapKey As String = ConfigurationManager.AppSettings("googlemaps.subgurim.net")
        Dim GeoCode As Subgurim.Controles.GeoCode

        sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia"
        GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng)

        GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
        GMap1.addGMarker(oMarker)

Press F5, and start basking in the glory!

Update: I’ve now posted the code to add draggable markers and events to your Google Maps