I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Related
I want to show user's current location and country name,city name on google map the code which I tried showing undefined for country and city name ,how to show country and city name on google map
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMnYWXbdpKU3t__MXrRMLAMer23E6gRjs"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
console.log(LatLng);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
console.log(map);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude+"<br/>Country:"+p.coords.country+"<br/>city:"+p.coords.city
});
google.maps.event.addListener(marker, "click", function (e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
You need to reverse geocode the position returned from the Geolocation service to get the country and city information.
geocoder.geocode({
'location': LatLng
}, function(results, status) {
console.log("geocoder callback status=" + status);
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
// from "Google maps API, get the users city/ nearest city/ general area"
// https://stackoverflow.com/questions/50081245/google-maps-api-get-the-users-city-nearest-city-general-area
var details = results[0].address_components;
var city;
var country;
console.log(JSON.stringify(details));
for (var i = details.length - 1; i >= 0; i--) {
for (var j = 0; j < details[i].types.length; j++) {
if (details[i].types[j] == 'locality') {
city = details[i].long_name;
} else if (details[i].types[j] == 'sublocality') {
city = details[i].long_name;
} else if (details[i].types[j] == 'neighborhood') {
city = details[i].long_name;
} else if (details[i].types[j] == 'postal_town') {
city = details[i].long_name;
console.log("postal_town=" + city);
} else if (details[i].types[j] == 'administrative_area_level_2') {
city = details[i].long_name;
console.log("admin_area_2=" + city);
}
// from "google maps API geocoding get address components"
// https://stackoverflow.com/questions/50225907/google-maps-api-geocoding-get-address-components
if (details[i].types[j] == "country") {
country = details[i].long_name;
}
}
}
console.log("city=" + city);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "<div style = 'height:80px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude + "<br/>Country:" + country + "<br/>City:" + city
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('dvMap'), {
zoom: 8,
center: {
lat: 40.731,
lng: -73.997
}
});
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
console.log(LatLng);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map.setOptions(mapOptions);
geocoder.geocode({
'location': LatLng
}, function(results, status) {
console.log("geocoder callback status=" + status);
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
// from "Google maps API, get the users city/ nearest city/ general area"
// https://stackoverflow.com/questions/50081245/google-maps-api-get-the-users-city-nearest-city-general-area
var details = results[0].address_components;
var city;
var country;
console.log(JSON.stringify(details));
for (var i = details.length - 1; i >= 0; i--) {
for (var j = 0; j < details[i].types.length; j++) {
if (details[i].types[j] == 'locality') {
city = details[i].long_name;
} else if (details[i].types[j] == 'sublocality') {
city = details[i].long_name;
} else if (details[i].types[j] == 'neighborhood') {
city = details[i].long_name;
} else if (details[i].types[j] == 'postal_town') {
city = details[i].long_name;
console.log("postal_town=" + city);
} else if (details[i].types[j] == 'administrative_area_level_2') {
city = details[i].long_name;
console.log("admin_area_2=" + city);
}
// from "google maps API geocoding get address components"
// https://stackoverflow.com/questions/50225907/google-maps-api-geocoding-get-address-components
if (details[i].types[j] == "country") {
country = details[i].long_name;
}
}
}
console.log("city=" + city);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "<div style = 'height:80px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude + "<br/>Country:" + country + "<br/>City:" + city
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
}
html,
body,
#dvMap {
height: 100%;
margin: 0;
padding: 0;
}
<div id="dvMap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
The code below display a map and display the results in UL. I have 2 buttons that display train station and shopping mall.Initially, it will display the results correctly but If I click the other button, it will display duplicate values.
Javascript
var map;
var pos;
var distance;
var distancearray = [];
var markers = [];
//=================================================================
function initialize() {
googleMapsLoaded = false;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var request = {
location:pos,
radius:3000, //3000 Meters
type:initialtype
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here',
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
else{
for (var i = 0; i < results.length; i++)
markers.push(createMarker(results[i]));
}
} //end callback function
/* listen to the tilesloaded event
if that is triggered, google maps is loaded successfully for sure */
google.maps.event.addListener(map, 'tilesloaded', function() {
googleMapsLoaded = true;
// document.getElementById("mapnotification").innerHTML = "Map Loaded!";
$("#mapnotification").hide();
$("#map-loaded").show();
$("#map-loaded").css('visibility', 'hidden');
$("#map-notloaded").hide();
//clear the listener, we only need it once
google.maps.event.clearListeners(map, 'tilesloaded');
});
setTimeout(function() {
if (!googleMapsLoaded) {
//we have waited 7 secs, google maps is not loaded yet
document.getElementById("mapnotification").innerHTML = "Map NOT Loaded! Make sure you have stable internet connnection";
$("#mapnotification").hide();
$("#map-notloaded").show();
$("#map-loaded").hide();
}
}, 7000);
function createMarker(place) { // Create Marker and the Icon of the marker
// var bounds = new google.maps.LatLngBounds();
var markerlat;
var markerlon;
var p2;
var output="";
var placesList = document.getElementById('places');
placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor:'00a14b',
fillOpacity:0.3,
fillStroke: '00a14b',
strokeWeight:4,
strokeOpacity: 0.7
}, // end icon
}); //end of marker variable
markerlat = marker.getPosition().lat()
markerlon = marker.getPosition().lng()
console.log("Markers Lat" + markerlat);
console.log("Markers Lon" + markerlon );
p2 = new google.maps.LatLng(markerlat, markerlon);
distance = [calcDistance(pos, p2)];
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
distancearray.push([distance, place.name]);
distancearray.sort();
console.log("distancearraylength" + distancearray.length);
console.log("Summary" + distancearray);
for(var i = 0; i < distancearray.length; i++){
output += '<li>' + distancearray[i][1] + " " + distancearray[i][0]+ " " + "km" + '</li>';
placesList.innerHTML = output;
}
google.maps.event.addListener(marker, 'click', function() { //show place name when marker clicked
infowindow.setContent(place.name);
infowindow.open(map, marker);
}); // end of marker show place name
} // end createMarker function
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
} // End handleNoGeolocation function
} //End function initialize
//==========================================================================================================//
$(document).on('pagebeforeshow','#itemPanel2', function(e, data){ // Loading of Nearest Place Options
bindchoicesclick();
function bindchoicesclick(){
$("#subway_station").on("click",function(){
// alert("subway");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
//$("#places").empty();
initialtype = ['subway_station'];
buttonholder = "Nearest Station";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
$("#shopping_mall").on("click",function(){
// alert("stores");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
// distancearray.splice(0).
// $("#places").empty();
initialtype = ['shopping_mall'];
buttonholder = "Nearest Mall";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
}
});
HTML
<h1 id="headerField">Nearby Search</h1>
</div>
Search Nearest Train Station
Search Nearest Mall
</div>
<!--Train Stations -->
<div id="globa_map" data-role="page">
<div data-role="header">
Back
Refresh
<h1 id="headerField">Global</h1>
</div>
<div data-role="content">
<!-- <input type="button" id="refreshmap" value="Refresh"> -->
<p id="mapnotification">Please wait while the map is loading...</p>
<p id="map-loaded">Map Loaded!</p>
<p id="map-notloaded">Map NOT Loaded! Make sure you have stable internet connnection</p>
<h2>Results</h2>
<ul id="places"></ul>
<button id="more">More results</button>
<div id="map" style="height:400px;">
</div>
</div>
I'm trying to make a select to show and hide markers with category.
Its working fine, but not working if there is a markercluster on map.
Eg. when i choose category bar markers on map with category restaurant disapear, but markercluster is still on map. Here is my intin function:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(52.6145, 21.3418);
var mapOptions = {
zoom: 6,
center: chicago
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
// Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
document.getElementById('field').value = +position.coords
.latitude + "," + position.coords.longitude;
marker = new google.maps.Marker({
position: pos,
animation: google.maps.Animation.DROP,
map: map
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("db/parse_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName(
"marker");
markerArray = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var cover = markers[i].getAttribute("cover");
var point = new google.maps.LatLng(parseFloat(markers[i]
.getAttribute("lat")), parseFloat(markers[i]
.getAttribute("lng")));
var html = "<div id='infobox'><img src='" + cover +
"'/><b>" + name + "</b><br>" + address +
" <br/><input type='button' id='end' onClick=calcRoute() name='" +
name + "," + address +
"' value='Wyznacz trasę'></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
category: type
});
markerArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
document.getElementById('pasekBoczny').innerHTML +=
'<li class="list-sidebar" ><a href="javascript:myclick(' +
i + ')" >' + name + '</a></li>';
// markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markerArray);
});}
and my filter function:
filterMarkers = function (category) {
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}}
I'm assuming you're not wanting to completely remove the marker clusters, just change those where you're hiding the markers. As you're looping over the markers, remove those you're hiding from the cluster, like so:
// Categories don't match
else {
marker.setVisible(false);
markerCluster.removeMarker(marker);
}
Similarly if you show the marker, you probably need to add it back into the cluster, using addMarker
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
markerCluster.addMarker(marker);
}
Then you probably need to call the redraw function on the MarkerClusterer.
See https://googlemaps.github.io/js-marker-clusterer/docs/reference.html
redraw() Redraws the clusters.
You'll need to amend your code to make the MarkerClusterer a global variable first. e.g.
var markerCluster;
function initialize() {
...
markerCluster = new MarkerClusterer(map, markerArray);
}
filterMarkers = function (category) {
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
markerCluster.addMarker(marker);
}
// Categories don't match
else {
marker.setVisible(false);
markerCluster.removeMarker(marker);
}
}
markerCluster.redraw();
};
I'm trying to develop a page using different scripts like google places autocomplete, the query with checkboxes (https://developers.google.com/fusiontables/docs/samples/in) and zooming on a place (http://www.geocodezip.com/v3_FusionTables_GViz_zoom2MarkerA.html).
The thing is, the autocomplete or checkboxes+zoom work fine on their own, but everything's wrong when combined!
I've tried to dislocate the code and re-assemble, but it doesn't work and I don't understand why.
I'm a total beginner in Javascript so I'm really testing and adapting things.
Many thanks if you have any clues!
The code with checkboxes + zoom:
// Checkboxes
layer = new google.maps.FusionTablesLayer();
filterMap(layer, FT_TableID, map);
google.maps.event.addDomListener(document.getElementById('0'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('1'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('2'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('3'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('4'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, FT_TableID, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Latitude',
from: FT_TableID,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var stores = document.getElementsByName('note');
for (var i = 0, note; note = stores[i]; i++) {
if (note.checked) {
var noteName = note.value.replace(/'/g, '\\\'');
filter.push("'" + noteName + "'");
}
}
var where = '';
if (filter.length) {
where = "'coeurs' IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
///// end of checkboxes part
//////// zoom
function changeQuery(term) {
layer.setOptions({query:{select:'Latitude', /* was 'Latitude,Longitude', used to work... */
from:FT_TableID,
where:"'Nom' contains ignoring case '"+term + "'"
//à la place de : where:"Nom contains "+term
}
});
// alert("query="+term);
// zoom and center map on query results
//set the query using the parameter
var queryText = encodeURIComponent("SELECT 'Latitude', 'Longitude' FROM "+FT_TableID+" WHERE 'Nom' contains '"+term+"'");
// does _not_ work var queryText = encodeURIComponent("SELECT 'Latitude' FROM "+FT_TableID+" WHERE District = "+term);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(zoomTo);
}
function zoomTo(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var bounds2 = new google.maps.LatLngBounds();
for(i = 0; i < numRows; i++) {
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 0)),
parseFloat(response.getDataTable().getValue(i, 1)));
bounds2.extend(point);
}
// zoom to the bounds
map.fitBounds(bounds2);
map.setZoom(18);
}
The code used for the autocomplete:
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(O, 0),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
google.maps.event.addDomListener(window, 'load', initialize);
there are two calls of initialize:
google.maps.event.addDomListener(window, 'load', initialize);
remove one of them.
I have a FF error about the info window in GM. Here is the source code:
var lats;
var longs;
var k;
function initialize() {
//parentArray is an object where the elements of the parent page are stored
var parentArray = window.parent.params;
lats = parentArray["lat"].replace(/^\|+|\|+$/g, '').split("|");
longs = parentArray["long"].replace(/^\|+|\|+$/g, '').split("|");
k = parentArray["keys"].replace(/^\|+|\|+$/g, '').split("|");
var myLatlng = new google.maps.LatLng(parseFloat(lats[0]), parseFloat(longs[0]));
var myOptions = {
zoom: 20,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//contentString is built based on the array passed by the parent page
for (var i = 0; i < lats.length; i++) {
var contentString = '<div id="content"' + i + '><b>' + k[i] + '</b>';
for (var f in parentArray)
if ((f !== "long") && (f !== "lat") && (f !== "keys") && (parentArray[f].substring(0, 1) !== "<")) {
contentString += '<br />' + f + ': ' + parentArray[f];
}
contentString += '<br /></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(lats[i]), parseFloat(longs[i])),
map: map,
title: 'Position'
});
createInfoWindow(marker, contentString);
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
}
}
params is an array with information and k is an array of keys for the markers on the google map. Does anybody know why do I have a FF error for this code?
Sample Data For params:
params['foo']: bar
params['keys']: "Start Position|End Position"
params['lat']: "12.5323703|13.5323703"
params['long']: "14.5786987|15.5786987"
EDIT:
The Error is: createInfoWindow is not defined
Thanks in advance,
Lajos Arpad.
You are defining your method inside a loop (this is bad on its own..) and you call the method before you define it ..
just moving the call below the definition fixes the issue..
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
createInfoWindow(marker, contentString);
Demo at http://jsfiddle.net/gaby/gdLVd/
But you should really move the definition of the createInfoWindow method somewhere else..
Better demo at http://jsfiddle.net/gaby/gdLVd/1/