User 'ben' not found. Maybe their WP key is set wrong.

2 October 2009

Simple Geo-location with Google Maps API and jQuery

For a recent project, we needed to generate a point on a map for an event. Without being able to explicitly click on the map to determine the location, we had to write up a quick geo-location script to find a latitude and longitude for the event. This was quite easy with the Google Maps API.

Firstly, you need to include the Google Maps API. You’ll need to replace YOUR_API_KEY with a valid API key for your site.

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_API_KEY&amp;sensor=false" type="text/javascript" language="JavaScript" charset="utf-8"></script>

We decided to use a bit of jQuery action to implement this. Here’s the final helper tool we wrote with some simple jQuery effects. I’ve populated the fields with our Seattle address for testing. Have a look at the source code and then come back:

Demo: Simple geo-coding with google maps and jquery

Here’s the bulk of the functionality with a lot of the effects stripped out. First we make sure jQuery is ready to do be used:

// make sure jquery is ready
$(document).ready(function()
{

Inside the ready callback function, instantiate a new instance of the Google geo-coder class:

var geocoder = new GClientGeocoder();

Then extend jQuery to create the geolocateAddress function. This function simply calls the getLocations method of the geocoder class. If there is a response, you can check the Placemark array of the response for your results. Usually–if your address is well formatted–the first item in the array will be your geo-located address:

$.geolocateAddress = function(address)
{
    // call the getLocations method of the geocoder class
    geocoder.getLocations(address, function(response)
    {
        if (response != null && response.Placemark != undefined)
        {
            var placemark = response.Placemark[0];
            var coords = placemark.Point.coordinates;
            var latLng = new GLatLng(coords[1], coords[0]);
        }
        else
        {
            // handle failure here
        }
    });
}

The important part is checking if the Placemark is set and then generating a latitude/longitude object from the result:

var placemark = response.Placemark[0];
var coords = placemark.Point.coordinates;
var latLng = new GLatLng(coords[1], coords[0]);

To call the code, simply add a hook to a button. In the example, I concatenated an address from the address, city and country fields in the form:

$("#submit").click(function(event)
{
    event.preventDefault();

    $("#address").attr("disabled", true);
    $("#city").attr("disabled", true);
    $("#country").attr("disabled", true);

    // generate the address
    var address = $("#address").val();
    address += " " + $("#city").val();
    address += " " + $("#country").val();

    // call the function with the address
    $.geolocateAddress(address);
});

That’s about it. If you’d like to download the demo, it’s located here. Just generate an API key on Google Maps and replace the $api_key variable at the top of the script.

User 'ben' not found. Maybe their WP key is set wrong.
0 ,

October 2nd, 2009 at 05:49 PM
Posted By: Ben Borowski in General

6 June 2009

@see snippet for TextMate

I’ve been doing a ton of work with the newest Zend Framework version 1.8.2 this weekend. At BKWLD, we’ve standardized on ZF for many of our sites and it’s also the base of our super-fancy BKWLD Unified CMS, so it behooves me to keep up with the latest hotness.

Since we are also always improving our standards and practices when it comes to coding and documentation, we’ve been using PHPDoc and ASDoc to create documentation for our code. I’ve found that typing out all the requires for each class can be a pain in php, so I made a quick TextMate snippet to make adding @see directives for phpdoc at the same time as the require_once directive. Here it is; simple but useful:

/**
 * @see $1
 */
require_once "${1/_/\//g}.php";$0

Add this as a “Tab Trigger” for the word “see” then just type “see” and hit tab then type your class name. It will auto fill the comment and the path to the pear-conventionally-named .php file.

Got any other useful TextMate snippets? Using something cool to document your code? Please do share!

User 'ben' not found. Maybe their WP key is set wrong.
0 ,

June 6th, 2009 at 02:13 AM
Posted By: Ben Borowski in General

5 April 2008

Save a Dev!

I did say that I wasn’t going to bother with IE6 fixes on my new site. In fact, I was planning on insulting IE6 users with a special graphic overlay. I remembered however that this would include people like

a) 50% of our clients (guessing)
b) 66% of my family (my brother introduced me to firefox)
c) 30% of everybody (according to current stats)

So, that’s a lot. So, I spent the whole day (literally) fixing the site for 6 (argh) + 7 (which was admittedly easy). Anyway, for the IE6 users, I’m using a little script from this site:

http://savethedevelopers.com/

It’s cool, it animates in a pretty image at the top of the page saying how you should upgrade and provides links to current/modern browsers. So, while not an affront to each users’ browsing sensibilities, it does provide a nice recommendation that is rather obvious.

Tags: , ,
User 'ben' not found. Maybe their WP key is set wrong.
3 ,

April 5th, 2008 at 07:52 PM
Posted By: Ben Borowski in Development

15 March 2008

Twitter kills flash apps

Twitter recently remade their crossdomain.xml file very restrictive, allowing only apps on their own domain to access the api content. Unfortunately, this makes Flash applications throw Sandbox violations so no more Flash/Twitter mashups. Apparently though, they aren’t above the possibility of selling access though. Discovering radiance? What the? Apparently, there’s a real security issue involved (flash 9, what’s new!?) but it’s a bummer b/c I really liked my little app that I made for my new site. Next up: Ben scrapes his twitter content, saves it locally. ;)

User 'ben' not found. Maybe their WP key is set wrong.
2 ,

March 15th, 2008 at 09:26 PM
Posted By: Ben Borowski in General

14 February 2008

Best parse error ever

Most certainly unexpected.

picture-1.png

(apparently it means “double colon” in hebrew)

User 'ben' not found. Maybe their WP key is set wrong.
0 ,

February 14th, 2008 at 11:09 PM
Posted By: Ben Borowski in General

29 January 2008

Hide Flash div without restarting movie/applet

I ran into an issue today with Flash and targeting the div wrapper (when using SWFObject). Basically, there seems to be a bug in Firefox (and possibly other browsers) that causes the applet to reload when changing its display state. I found that instead of using

document.getElementById('flash_div').style.display = 'none';

that by using an explicit dimension you can achieve the same result without restarting the applet:

document.getElementById('flash_div').style.height = '0px';

Not sure if Firefox 3 addresses this. I’m guessing it does.

EDIT
ARGH. Setting the height to 0 definitely hides it, but little pieces of the flash are still active. Guess it’s an official “bug.”

User 'ben' not found. Maybe their WP key is set wrong.
3 ,

January 29th, 2008 at 04:22 PM
Posted By: Ben Borowski in Development

21 December 2007

Handling remote content with Loader class and security

Doing some work with Flickr’s API and Actionscript 3 today. When I finally exported my file, the Event.INIT associated with the Loader didn’t seem to be firing the way I thought it would. I was resizing an image after it had initialized, but it seemed to only work in the Flash IDE. Here’s what I started with:

private var _image:Bitmap;

public function Image (url:String):void  {
	loader = new Loader();
	loader.contentLoaderInfo.addEventListener(Event.INIT, onInit);
        addChild(loader);
        var request:URLRequest = new URLRequest(url);
        loader.load(request);
}

private function onInit (event:Event):void {
        _image = Bitmap(event.target.content);
}

This code works great for loading an image on a local server or in the flash player, but my code to resize the image on init was not being run when the movie was embedded in a browser. So, I added this and figured out that it was throwing an error:

private function onInit (event:Event):void {
        try{
                _image = Bitmap(event.target.content);
        } catch (error:SecurityError) {
                trace(error);
        }
}

This basically “trys” to access the content of the loader and if it can’t, throws a SecurityError (#2122). Flickr has a crossdomain.xml file that allows all access (”*”) so I was confused as to why it was throwing this error. Turns out with AS3 that you have to TELL it to check the crossdomain file. So, my new load function now looks like this:

var context:LoaderContext = new LoaderContext(true);
var request:URLRequest = new URLRequest(url);
loader.load(request, context);

The “true” param in LoaderContext let’s Loader know that it should checkPolicyFile. Trouble is, even after checking the policy file, I was still getting the SecurityError. Finally, with all this data in hand, I did some googling and found this. Seems that perhaps there’s some kind of redirect on the asset we are accessing, so we need to continue to hit the url with the policy file to get a valid asset. Here’s what the final init function looks like (in general):

private function onInit (event:Event):void {
	if (event.target.childAllowsParent == false) {
		load(event.target.url);
	} else {
		_image = Bitmap(event.target.content);
		dispatchEvent(new Event(Event.INIT));
	}
}

I had thought it was another Event.INIT firing problem but it turns out it was a sandbox violation.

User 'ben' not found. Maybe their WP key is set wrong.
0 ,

December 21st, 2007 at 01:12 PM
Posted By: Ben Borowski in General

18 December 2007

Flash Keyboard Events Not Working…Duh.

I’m doing some work with flash.ui.Keyboard today. During testing in the Flash environment, every time I pressed (for example) the ‘F’ key, it was shifting focus to the Tools ‘Fill Transform’ tool and therefore not registering the event. To get around this, I made a copy of my shortcuts and removed all the tool shortcuts. However, the Keyboard was not registering Keyboard.BACKSPACE presses and some of the other keys. After some poking around, I found this little number when previewing the SWF … Control > Disable Keyboard Shortcuts. Duh! This makes sure than the IDE is not receiving the Keyboard events during preview.

User 'ben' not found. Maybe their WP key is set wrong.
2 ,

December 18th, 2007 at 10:10 AM
Posted By: Ben Borowski in General

21 November 2007

Remove SVN files with automator

We’ve been using subversion pretty extensively recently and loving the idea of it (though it is rather finicky). When reusing files for multiple projects, often you’ll want to just copy and paste folders and files right into another project. This poses a problem when using subversion because if the folder already contains .svn files, you won’t be able to add it to another repository. So, you first must delete those files. This is the command line script we’ve been using to remove them (recursively from the directory you are currently in):

find . -name .svn -print0 | xargs -0 rm -rf

It’s a pain having to open terminal though, so here’s a nice way of accomplishing the same result using Automator:

You can find all of these actions under “Applications” in the Automator Library. Starting with (1) Ask for confirmation, we prompt the user to make sure they want to continue. (2) Gets a list of selected finder items [if you had a group of directories selected, it makes a list of those]. At (3), the script we were using before is run on each item (removing the “.svn” file in each directory):

for f in "$@"
do
	find "$f" -name .svn -print0 | xargs -0 rm -rf
	echo "$f"
done

Then at (4) it outputs the list of items cleared to a text file on the desktop. When compiling to a plug-in (explained further down) I have this “disabled” so I don’t get that textfile every time. Perhaps you could do something like output the results to the console.

You can then go to File > Save As Plugin… Save the file (I called it “ClearSVN”) as a Plug-in for: Finder. This enables you to right click a directory, go to Automator… and select “ClearSVN” which would clear the .svn files inside that directory!

NOTE that this is for OS Tiger. In Leopard, the actions seem to be slightly different, but could be updated to work the same way.

Download source

Tags: ,
User 'ben' not found. Maybe their WP key is set wrong.
9 ,

November 21st, 2007 at 12:07 PM
Posted By: Ben Borowski in Development

Flash player crashes browser when closing window (possible fix)

Working with ActionScript 3, we’re finding plenty of bugs that others have found and have experienced some intermittent crashing due to garbage fonts, but yesterday we had a doosy that lasted all day. The site was running fine and frame-rates were great, but we could pretty consistently crash (or at best get a spinning color wheel on ) any browser (safari, firefox, ie 6 + 7, mac, windows) when you closed the window containing the flash movie (closing the browser window with a hot key or clicking the close button). We started by removing all our code; first papervision code, then removing the content that was being displayed, then all embedded fonts … it was pretty stripped down. It was not until the content was removed that the browser crashes subsided. So, we started googling the hell out of “flash player 9 crashes closing window” and randomly came across this post where user nikonratm noted the following:

Tweening the position of a TextField that has a mask, as soon as I close the movie window the program crashes, whether it be in the Flash (CS3) IDE or in a browser.

This was the first instance we had found where the crash was specific to closing the window. So, we went through and removed all masking and no crashes. We then added each mask back and tested and got to a point where we slimmed down the crash culprit as a directly masked text field that had a TextFormat applied to it (also it had embedded fonts, not sure if that had anything to do with it), i.e. a TextField that had a mask applied to it and not a DisplayObject containing a text field with a mask appled to the DisplayObject. You always had to put text inside MovieClips to dynamically mask in AS2 so it seems that either the implementation is faulty in AS3 or just moving or changing the text after it has been masked causes some kind of memory leak (which causes the browser to crash on close). Something like this:


var titleMasked:TextField = new TextField();
titleMasked.mask = gradient;

Perhaps a fix would be to put the text inside a sprite (at this point, I’ve spent so much time I’m not bothering to test it):


var titleSprite:Sprite = new Sprite;
var titleMasked:TextField = new TextField();
titleSprite.addChild(titleMasked);
titleSprite.mask = gradient;

To fix some of these issues, Adobe seems to think downgrading to flash player 8 is a good idea. Should we also go back to AS2 while this is resolved? I’m ready to after yesterday. Their solutions to bugs leave something to be desired. For example, one of their comments regarded the Loader classe’s inability to close streams when uploaded:

You cannot expect an “unloaded” movie to close its net streams automatically.

Well, it may not close the stream automatically, but if you create method called “unload,” I’m going to have the expectation that it’ll unload something. Perhaps there’s an undocumented unloadAndCloseStreamAutomatically.

Tags: ,
User 'ben' not found. Maybe their WP key is set wrong.
8 ,

November 21st, 2007 at 09:29 AM
Posted By: Ben Borowski in Development