søndag 16. november 2014

Google Map and working with Markers - making it disappear

Hi there!

This particular blog post is a result of me spending hours to find a solution. This fall I have been working with HTML5 as a subject on my journey of getting a bachelor degree. And the end term project is to make a solution which updates a map with information regarding whether there are or are not free parking spaces in one of four parking areas.
The incoming data is a simulated Server Sent Event which sends data each 5 seconds.

Regarding the state of the area the markers are going to change color. Red if full, yellow if less than 20% and blue if more than 20% free parking spaces. In addition the user is supposed to be able to set a limit of minimum free parking spaces in a parking zone using a slider. If it is too few parking spaces available, the marker for that area is supposed to disappear. For this project I made my own custom made markers.

And this is where the problems that led to this blog post starts.

For my solution I chose to go for the google map api, which is the one most likely to be used if I ever get a web page developer position. At this point I had completed too much of the project to go back and start over regarding my time limit. As always I tend to go for a solution that is 1 part by the book and 1 part by my head, and my head had been making this part extra difficult. If you read up on google api multiple markers, they tend to go for an array of markers. I had done no such thing.

I had made if-statements for the placement of each marker on the map. Something like this:

if ((parkingStatus == total) && (userInput === 0)) {
image = 'img/red.png;
}

In googles map api documentation and on the pages of stackoverflow.com the advice to hide the markers were:

Google Remove Markers
https://developers.google.com/maps/documentation/javascript/examples/marker-remove

Stackoverflow:
http://stackoverflow.com/questions/3647711/what-is-the-difference-between-marker-setvisiblefalse-and-marker-setmapnul

Well... none of these worked for me, so I thought that I could use something like this:

if (free<= userInput) {
image = '';
}

This only replaced my custom made marker with google map standard marker.

After I had been giving this some thought I came up with the solution. What I wanted to appear on the map was NULL. So I changed my If-statement so it looked like this:

if (free<= userInput) {
image = 'NULL';
}

This actually worked! So whenever the simulated Server Sent Events changes the free parking spaces to something less than the user sets as a limit, that marker disappears, and it reappears when the conditions change. No buttons involved.

If I do not get broken up into bits or adopt a binary form it will soon be a new blog with new experiences from my IT adventures!