How to make openInfoWindowHtml work in Google Maps 2 - google-maps

I'm setting up a extjs panel with a GMap2 embedded. Here's the setup:
map = new GMap2(document.getElementById("gmappanel"));
map.setCenter(new GLatLng(58.019257, -115.572402), 3);
map.setUIToDefault();
I'm using the example from here so that when I click a marker, I get an info window. The problem is, the event fires and I can see the proper HTML in the console, but nothing else happens. The info window simply doesn't open. no error, nothing.
Here's the code for that:
function createMarker(point, val) {
var marker = new GMarker(point);
var name = val.data.name;
var html = "<table class='marker'>";
html += "<tr><td>Name: </td><td>" + name + "</td></tr>";
html += "</table>";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
debug("Marker fired");
});
return marker;
}
Here's how I call it:
var marker = createMarker(point,store.getAt(i));
Any ideas?

Sounds like your HTML is not valid. Can you dump some example html data that you are passing to the openInfoWindowHtml? Your createMarker function works just fine with :
var html = "<table class='marker'><tr><td>Name: </td><td> sometext </td></tr></table>";
what version of the api are you using? 2.x?

Possibly you want bindInfoWindowHtml, not openInfoWindowHtml.
Something along the lines of..
function createMarker(point, val) {
var marker = new GMarker(point);
var name = val.data.name;
var html = "<table class='marker'>";
html += "<tr><td>Name: </td><td>" + name + "</td></tr>";
html += "</table>";
marker.bindInfoWindowHtml(html);
return marker;
}

You also have two marker variables defined in different scopes, check to make sure you have the listener on the right "marker".

Related

Add html asynchronously

I want to add new html in page asynchronously like
$.each(programListAll, function (j, innerItem)
{
programHtml = '<div class="row"><ul>';
$("#programList").append(programHtml);
});
It should show user that html is adding asynchronously.
How can I achieve this?
You could have a little delay in adding the items, the code would look like this:
var $programHtml = $('<ul class="row"></ul>');
$('#programList').append($programHtml);
var delay = 1000;
$.each(programListAll, function (j, innerItem)
{
$programHtml.delay(j * delay).append('<li'> + innerItem + '</li>');
});

How to initialize a google maps on pageinit without repeatingly loading the google map api script

I would like to be able to load the Google.maps API only once for alle my pages.
Then i would like to be able to use geolocation or loading a map into a page anywhere on my web app.
The problem is that I cant figure out to seperate API loading and map initialization.
Which means i need to load the API each time I create a map.
I have referenced most of my code further down in the post but i suppose the following code is the problem.That piece of code takes care of the API Loading but at the same time it takes care of setting the initialize() function as a callback function and calling it.
var script = document.createElement("script");
script.type = "text/javascript";
script.src ="http://maps.googleapis.com/maps/api/js?key=mykey&sensor=false&callback=initialize";
document.body.appendChild(script);
How do i load the api once, lets say in the header, and then create a new map each time I go to specific page. WIthout loading the maps API again. (Note that im using Jquery mobile so my header only gets loaded one time for a session.)
I get this error:
Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
Ii would like to tell you my setup.
-Im using Google Map APi v3
-I'm loading the API dynamically after the page has loaded.
-I'm using Jquery mobile, which means the page with google maps only gets partially reloaded when you visit it.
-Im using google maps for two things to show the map and for geolocation.
-I'm using the Google map api on several pages.
Im interacting with the map in 3 different places: In a header javascript see code below
A header javascript
A javascript in the body
The DIV in the body that holds the map.
Here is my code for the javascript that handles loading the API, showing the map, markers etc:
<script>
$('.error').hide();
//search criterias
var radius;
var timerange;
var type;
//user position variables
var userposition = false;
var mylatitudedegree = "=55.698";
var mylongitudedegree = "=12.579";
//map variables
var mapready = false;
var map;
var bound;
var markersArray = [];
//array for keeping track of the markers
var markercenter;
//hack
var pageinit = 0;
var initializer = 0;
var triggersearch = 0;
var loadscripts = 0;
var isgooglemapsloaded = false;
$( '#soegsagside' ).live( 'pageinit',function(event)
{
pageinit++;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, function(error) {
alert('Din location er ikke tilgængelig! Error code: ' + error.code);
userposition = false;
}, {
maximumAge : 60000,
timeout : 10000,
enableHighAccuracy : true
});
}
else {
alert("Din browser tillader ikke, at vise din lokation!");
userposition = false;
}
loadScript();
$("#search_filter_button").click(function() {
//hide the "skal udfyldes" labels
$('.error').hide();
// validate and process form here
radius = $("select#choose_radius_select").val();
if (radius == "vælg") {
$("label#radius_error").show();
$("select#choose_radius_select").focus();
return false;
}
timerange = $("select#choose_timerange_select").val();
if (timerange == "vælg") {
$("label#timerange_error").show();
$("select#choose_timerange_select").focus();
return false;
}
type = $("select#vælg_type").val();
if (type == "vælg") {
$("label#select_type_error").show();
$("select#vælg_type").focus();
return false;
}
//------------------post to php script ---------------
var dataString = 'radius=' + radius + '&timerange=' + timerange + '&type=' + type + '&mylatitudedegree=' + mylatitudedegree + '&mylongitudedegree=' + mylongitudedegree;
$.ajax({
type : "POST",
url : "soegsagDB.php",
data : dataString,
success : function(data) {
$('#søgeresultater').html(data);
$('#søgeresultater').trigger('create');
clearOverlays();
createtaskmarkers();
findCenterOfMarkers();
if (userposition) {
usergeoposition = new google.maps.LatLng(mylatitudedegree, mylongitudedegree);
map.setCenter(usergeoposition);
createuserposition(usergeoposition);
} else {
map.setCenter(markercenter);
}
expandMapBoundForMarkers()
}
});
//end of post search query to server
return false;
});
//end of click seach button
});
//end of page ready
function setPosition(position) {
userposition = true;
myposition = position.coords;
mylatitudedegree = position.coords.latitude;
mylongitudedegree = position.coords.longitude;
var milli = new Date();
}
//function for clearing the markerArray
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
//Function for initializing the map, which is called when the map is created
function initialize() {
initializer++;
bound = new google.maps.LatLngBounds();
var mapOptions = {
zoom : 13,
center : new google.maps.LatLng(55, 12),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
//Create a map
map = new google.maps.Map(document.getElementById("map"), mapOptions);
mapready = true;
$("#search_filter_button").trigger('click');//Trigger click on the search button
triggersearch++;
}
//create user positio marker
function createuserposition(usergeoposition) {
var userPositionMarker = new google.maps.Marker({
position : usergeoposition,
map : map,
title : "Din position",
});
markersArray.push(userPositionMarker);
}
function createtaskmarkers() {
//Create the markers of the tasks
//1. find the task <li> that contain the data and loop through each one
//2. for each task collect the dato into variables and create markers and infowindows
//3. calculate center of point
//4. extendt map area to contain all points
var data = $.map($('li'), function(element) {
if (element.hasAttribute("data-latitude")) {
var tempPos = new google.maps.LatLng($(element).attr('data-latitude'), $(element).attr('data-longitude'));
var link = $(element).attr('data-link');
var title = $(element).attr('data-title');
var type = $(element).attr('data-type');
var date = $(element).attr('data-date');
tempMarker = new google.maps.Marker({
position : tempPos,
map : map,
title : title,
});
tempMarker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var tempContentString = '<div style="width: 200px; height: 100px;">' + date + '<br></br>' + '<b>' + type + ' , ' + title + '</b>' + '</div>';
//Create infowindow
var tempInfowindow = new google.maps.InfoWindow({
content : tempContentString
});
//add market to markerArray
markersArray.push(tempMarker);
//Create event with infowindow
google.maps.event.addListener(tempMarker, 'click', function() {
tempInfowindow.open(map, this);
});
}
});
}
function findCenterOfMarkers() {
//calculate center of markers and change mapcenter to that
var sumlatitude = 0;
var sumlongitude = 0;
for ( position = 0; position < markersArray.length; position++) {
sumlatitude += markersArray[position].getPosition().lat();
sumlongitude += markersArray[position].getPosition().lat();
}
avglatitude = sumlatitude / markersArray.length;
avglongitude = sumlongitude / markersArray.length;
markercenter = new google.maps.LatLng(avglatitude, avglongitude);
}
function expandMapBoundForMarkers() {
//Extend bounds for map to fit all markers into map
for (var i in markersArray) {
bound.extend(markersArray[i].getPosition());
}
map.fitBounds(bound);
}
//loads the google maps api with KEY and appends the script to the document body
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyC8wZ6RmFySy0DnWvrUaA-2OJqcM1_AOIc&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
The only thing in the body of the page that has to do with the maps. Is the DIV that the map is loaded into.
<div id="map" style="width: 80%; height: 280px; margin: auto; background-color: gray">Kortet loader, vent venligst.</div> <!--alternative for full screen style="position:absolute;top:30px;bottom:50px;left:0;right:0;"-->
The API is also loaded in a common header script. Because I in general need to load it on other pages.
<script src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script type="text/javascript">
$(document).ready( function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=mynamespace.init_google_maps";
document.body.appendChild(script);
$(document).bind('pageinit', function() {
//do stuff here that happens each time a new page is loaded
});
});
});
</script>
the api is loaded once inside .ready(). you can create a new map in the callback that was passed to .bind() which is called each time a new page loads or is inserted. you can initialize the map inside mynamespace. mynamespace is a .js file included on the page

getting the right variables in a foreach loop (flex - googlemaps)

I'm trying to get specific variables out of a for each loop. These variables are used to display a click event on a marker on a map. If you click the marker on the map, the details pop over it. Now these details are being overwritten each time the loop starts (50 times). The solution I'm looking for, let's me select a marker on the map with the according detail attached to it.
There might be an easy solution but I haven't found it yet.
The code :
for each(artistXML in artistList.events.event)
{
var gLat:int = artistXML.venue.location.*::point.*::lat;
var gLong:int = artistXML.venue.location.*::point.*::long;
var evntLng:LatLng = new LatLng(gLat,gLong);
var title:String = artistXML.title;
var wanneer:String = artistXML.startDate;
var waar:String = artistXML.venue.location.city;
var pic:String = artistXML.venue.image.(#size=="medium");
var marker:Marker = new Marker(new LatLng(gLat, gLong));
var info:InfoWindowOptions = new InfoWindowOptions();
marker.addEventListener(MapMouseEvent.CLICK, function(event:Event):void {
var marker:Marker = event.target as Marker;
marker.openInfoWindow(new InfoWindowOptions({contentHTML: "<p><b>" + title + "</b></p><br/><p>" + wanneer + "</p> <br/> <p>" + waar + "</p>"}));
});
map.addOverlay(marker);
Goverlay++;
}
Thanks
You need to store a reference to the values somewhere before you start the next loop.
I'm not sure what the structure of your Marker and InfoWindowOptions classes are, so there might be a better way, but here's a naive solution:
Create 2 arrays called mapMarkers and infoWindows. For each loop push the new Marker and the new InfoWindowOptions instances into the appropriate arrays. You'll need to set those variables on the InfoWindowOptions too. Then in your click handler you can lookup the index of the Marker that was clicked (mapMarkers.indexOf(marker)) and use that index to get the corresponding InfoWindowOptions.

problem with openInfoWindowHtml for multiple points using events

I am a beginner and using openInfoWindowHtml to show the balloon text. my application has an option to show single location and multiple location.
My single location balloon text works fine using openInfoWindowHtml();
But when i go in for multiple, it always shows the last points text and the click event for all the points never happens.
code snippet:
var markers =[];
for(var i=0;i<(geoList.length)-1;i++)
{
var geo = (geoList[i]).split(',');
map.setCenter(new GLatLng(geo[3], geo[4]), 2);
var ip_point = new GLatLng(geo[3], geo[4]);
//creating a marker
marker = new GMarker(ip_point);
map.addOverlay(marker);
markers[i] = marker;
// The ballon text which shows the details of the ip address
var ip = "<div style=\"font-family:Verdana;font-size:10px;text-align:left\">";
//var dbName = base64_decode(geo[5]); // added on 14Dec2009
//If IP is not found it goes to else loop
if(geo.length== 9){
ip += "<span class=\"FSColorBold\">"+geo[5]+"</span><br /> ";
ip += "<?php __('IP:'); ?>"+geo[6]+"<br />";
ip += "<?php __('ID:'); ?>"+geo[7]+"<br />";
ip += "<?php __('Last Accessed: '); ?>"+geo[8]+"<br />";
ip += geo[2]+","+geo[1]+"<br />";
}
}
// shows IP details info by default
map.openInfoWindow(map.getCenter(),ip);
// Reloads the IP details info on clicking the marker
GEvent.addListener(marker, "click", function(){
marker.openInfoWindowHtml(ip+'');});
The points are in a loop and the event listeners are outside the loop.
Can anyone tell me exactly what went wrong?
You are only associating the click event with the last marker. You need call GEvent.addListener for each marker that you are adding to the map.
You also need to make sure that when the event is fired the marker in the callback is the marker that you associated with the event. You can do that by moving your marker creation code into a separate function (takes advantage of Javascript Closures to ensure the marker in the callback is the marker in scope in the outer function).
Check out this example based on your sample (code).

Customize Google Maps info window?

I'm working on a website of a client, a local church. I've embedded a Google Map using the Link feature on the Maps page. The info window on the map includes "Reviews," and the church is concerned about this. Is there a way to remove that from the info window? I don't want to remove any reviews themselves, just that link on the info window?
Is this possible? Are there any other customization options (besides the size) one can manipulate via the query string?
Nearly 2 years ago, I created a custom map with complete control over the contents of the bubble, using the API and some code manipulation. Click on the above link for a demo. I've cleaned up the code for this answer, although to implement you'll need to replace all YOUR__BLANK__HERE text with the appropriate values.
Step 1: Call the gMaps API
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY_HERE"
type="text/javascript">
</script>
Step 2: In the body of your document, create an element with id "map". Size and position it with CSS. It requires a height and width.
<div id="map" class="content"></div>
Step 3: After the div has been defined in the DOM, it is safe to insert the following script tag:
<script type="text/javascript">
//<![CDATA[
// Check to see if this browser can run the Google API
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
// The info window version with the "to here" form open
to_htmls[i] = html +
'<br />Start address:<form action="http://maps.google.com/maps" method="get">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
// "(" + name + ")" +
'"/>';
// The inactive version of the direction info
html = html + '<br><a href="javascript:tohere('+i+')">Get Directions<'+'/a>';
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
return marker;
}
// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
// Display the map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
YOUR_ZOOM_LEVEL_HERE // a value of 13 worked for me
);
// Set up one marker with an info window
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
/* repeat the process to add more markers
map.addOverlay(marker);
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
map.addOverlay(marker);*/
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://www.econym.demon.co.uk/googlemaps/
//]]>
</script>
Using this code, the bubble contains the html you specify in YOUR_HTML_HERE plus a link to Get Directions, which (when clicked) turns into a textbox asking for a starting address. The result of the query, unfortunately, opens in a new browser window (since, at time of original publishing the API did not include directions capabilities)
I think I found the answer to my own question. The info window itself can't be modified, but by linking to the map for the address itself rather than the church as a business entity does the trick. The driving directions link is still there and that's mostly all they wanted.