Google Maps populate text field with additional detail - javascript

I am trying to populate a text field with a dblclick event using information from a database. When I double click on the marker, the incorrect information is used to populate the fields. I get the same values for any marker I double click on. I have tried various ways to reference the colid, driver and vehicle values, but if I change anything, all I get is an unknown values in the field.
map = new google.maps.Map(document.getElementById("map"), map_options);
var infoWindow = new google.maps.InfoWindow;
downloadUrl(url, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var ThisMarker = markers[i];
var InfoText = ThisMarker.getAttribute("InfoText");
var colid = ThisMarker.getAttribute("colid");
var driver = ThisMarker.getAttribute("driver");
var vehicle_reg = ThisMarker.getAttribute("vehicle");
var mtype = ThisMarker.getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(ThisMarker.getAttribute("lat")),
parseFloat(ThisMarker.getAttribute("lng"))
);
var icon = customIcons[mtype] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
clickable: true
});
bindInfoWindow(marker, map, infoWindow, InfoText);
if(mtype == 'col' || mtype == 'del') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("collivery_id").value = colid;
document.getElementById("command").value = 'action';
});
}
if(mtype == 'bike' || mtype == 'car' || mtype == 'bakkie' || mtype == 'truck') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("driver").value = driver;
document.getElementById("vehicle").value = vehicle_reg;
});
}
}
});
function bindInfoWindow(marker, map, infoWindow, InfoText) {
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(InfoText);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infoWindow.close(map, marker);
});
}

Possible solution using function closure:
map = new google.maps.Map(document.getElementById("map"), map_options);
var infoWindow = new google.maps.InfoWindow;
downloadUrl(url, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var ThisMarker = markers[i];
var InfoText = ThisMarker.getAttribute("InfoText");
var colid = ThisMarker.getAttribute("colid");
var driver = ThisMarker.getAttribute("driver");
var vehicle_reg = ThisMarker.getAttribute("vehicle");
var mtype = ThisMarker.getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(ThisMarker.getAttribute("lat")),
parseFloat(ThisMarker.getAttribute("lng"))
);
var icon = customIcons[mtype] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
clickable: true
});
bindInfoWindow(marker, map, infoWindow, ThisMarker);
});
function bindInfoWindow(marker, map, infoWindow, marker)
{
var InfoText = marker.getAttribute("InfoText");
var colid = marker.getAttribute("colid");
var driver = marker.getAttribute("driver");
var vehicle_reg = marker.getAttribute("vehicle");
var mtype = marker.getAttribute("type");
if(mtype == 'col' || mtype == 'del') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("collivery_id").value = colid;
document.getElementById("command").value = 'action';
});
}
if(mtype == 'bike' || mtype == 'car' || mtype == 'bakkie' || mtype == 'truck') {
google.maps.event.addListener(marker, 'dblclick', function() {
document.getElementById("driver").value = driver;
document.getElementById("vehicle").value = vehicle_reg;
});
}
// whatever code is currently in your bindInfoWindow function
// possibly this:
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(InfoText);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infoWindow.close(map, marker);
});
}

Related

Laravel fetch longitude and latitude from database and display markers on Google Map

Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}

Google Maps API: Markers from XML file not being displayed

Using code that was posted on here, I'm trying to map markers from an XML file to a Google Map in a JSP using the Google Maps Javascript API V3.
My markers file has the following format:
<markers>
<marker>
<id>0</id>
<lat>53341428</lat>
<lng>-6246720</lng>
<name>Fenian Street</name>
<number>63</number>
</marker>
<marker>
<id>1</id>
<lat>53346637</lat>
<lng>-6246154</lng>
<name>City Quay</name>
<number>99</number>
</marker>
And the code is:
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'`enter code here`
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl( "markers.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = markers[i].getElementsByTagName("id")[0];
var point = new google.maps.LatLng(
parseFloat(markers[i].getElementsByTagName("lat")[0]),
parseFloat(markers[i].getElementsByTagName("lng")[0]));
var name = markers[i].getElementsByTagName("name")[0];
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: image
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState === 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {
}
</script>
When I load the page, I see an error in he console: InvalidValueError: setTitle: not a string
What am I doing wrong? The markers are not appearing on the map.
You are getting that error because "name" is not a string, it is an XML DOM object. There is a function nodeValue that can be used to get the string content out of an XML DOM element.
Also, your latitude and longitude are not valid, they are not in decimal degrees.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// downloadUrl( "markers.xml", function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlString);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = nodeValue(markers[i].getElementsByTagName("id")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName("lat")[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName("lng")[0])));
var name = nodeValue(markers[i].getElementsByTagName("name")[0]);
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: ""+name /*,
icon: image */
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
// });
}
where nodeValue was "borrowed" from geoxml3:
//nodeValue: Extract the text value of a DOM node, with leading and trailing whitespace trimmed
function nodeValue (node, defVal) {
var retStr="";
if (!node) {
return (typeof defVal === 'undefined' || defVal === null) ? '' : defVal;
}
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
};
working fiddle

Scope issues when trying to clear Google map markers

I created a google map with this code:
function load() {
var markersArray = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("getMapMarkers.php", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var brewID = markers[i].getAttribute("brewID");
//construct url
var breweryLink = "http://beerportfolio.com/breweryPage.php?id=" + brewID;
//create directions link
http://maps.google.com/maps?daddr=
var directionsLink = "http://maps.google.com/maps?daddr=";
directionsLink = directionsLink + markers[i].getAttribute("lat") +"," + markers[i].getAttribute("lng")
var html = "<b>"+name+" </b> <br/>" ;
html = html + "<br> <br>";
html = html + "(Click for Directions)";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
bounds.extend(point);
}
map.fitBounds(bounds);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function getMapVisit()
{
alert("clearing overlays...");
clearOverlays();
return false;
}
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function doNothing() {}
When I try an delete the markers to re-load different ones, I cannot delete them off the map.
On button press I call getMapVisit() which then calls clearOverlays(), but clearOverlays() doesn't clear the map. In Chrome, when I inspect the element I get this error:
Uncaught ReferenceError: markersArray is not defined
The error is called on line 86 which is:
if (markersArray) {
I do not know why its not defined when its clearly initialized array at the top of load()
You need to define var markersArray = []; above the load function so it will be globally defined and will be accessible in all the functions .

Permanent Google Map Infowindow

I have a marker which has a dynamic position (i.e. updated periodically). When marker is clicked, an infowindow is shown but when marker position is updated, the infowindow gets automatically closed. I want that when marker position is updated, infowindow position should also get updated automatically. How to solve this.
P.S. :- infowindow contain a form which is editable by the user.
Problem : when user is editing/filling the form and marker position gets updated (form not submitted yet), then the form will get closed and user will lose his data.
<script type="text/javascript">
var map;
var lat_longs = new Array();
var geocoder = null;
var infoWindow = new google.maps.InfoWindow();
var trafficLayer = null;
var weatherLayer = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
loc_array = new Array();
totUpdateOld = new Array();
ident = 0;
function showMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng('-0.57128','117.202148'),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
showCarPosition(function() {
fitMapToBounds();
});
}
function showCarPosition(){
if (markers.length>0){
ident = 2;
}
var car_icon;
jQuery.getJSON('<s:property value="jsonUrl"/>','', function(data) {
var arrayCar = data.listCar;
for (var i = 0; i < arrayCar.length; i++) {
var car = arrayCar[i];
var status = "";
var tanggal = "never";
var car_type = (car.type != "" || car.type != null)?' ('+car.type+')':'';
if(car.lastUpdate == null){
car_icon = ctx + 'web/img/car_black.png';
status = "Belum pernah kirim data";
}else if((not_active = (currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 30){ //diff in minute
car_icon = ctx + 'web/img/car_red.png';
status = convertMinute(not_active);
}else if((((currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 5) && (car.lastSpeed == 0)){ //diff in minute
car_icon = ctx + 'web/img/car_yellow.png';
status = "Berhenti";
}else
car_icon = ctx + 'web/img/car_green.png';
if(car.lastUpdate != null){
var splitDate = car.lastUpdate.split("T");
tanggal = splitDate[1]+" "+splitDate[0].split("-")[2]+"-"+bulan[parseInt(splitDate[0].split("-")[1])]+"-"+splitDate[0].split("-")[0];
}
var coordinate = new google.maps.LatLng(car.latitude, car.longitude);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li class="active">'+car.plate +car_type+' - '+ car.driverName +'</li>',
(status != null)?'<li>'+status+'</li>':'',
(car.phoneNumber != null)?'<li>Phone : ' + car.phoneNumber+ '</li>':'',
'<li>Last Temp : ' + car.lastTemp+ '</li>',
(parseInt(car.lastSpeed)>0)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
(car.type != "" || car.type != null)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
'<li>Last Connected : ' + tanggal+ '</li>',
'<li>'+((car.note != null)?car.note:'no notes')+'<li>',
'<div id="'+car.id+'"></div></ul>',
'<span id="'+car.id+'" onclick="editinfo(this, \''+car.note+'\');">Edit Note</span></div>']
.join('');
if (ident == 0){
var marker = createMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
loc_array[car.id] = i;
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}else{
if (car.totalUpdate > totUpdateOld[car.id]) {
var map_post = loc_array[car.id];
markers[map_post].setMap(null);
var marker = updateMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
}, map_post);
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}
}
totUpdateOld[car.id] = car.totalUpdate;
}
fitMapToBounds();
});
setTimeout("showCarPosition()",5000);
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
jQuery(document).ready(function() {
showMap();
});
</script>
<div id="map_canvas" class="widgettitle" style="height:540px;"></div>
call this function when the marker position is changed .
infowindow.open(map,marker);
Put an onblur event handler on the text field that calls a halt to the repositioning.
Then when it is submitted and goes to the new point, restart it (if needed).

Dynamically populated google maps sidebar

I've been using the code from this V3 example to set up a links bar that dynamically populates when different category filters are selected, but have two problems at the moment. Firstly, I've put the the initial makeSidebar function in the map's idle event, but the sidebar is only created when the map is moved, not on loading of the page. Secondly, I can't seem to get the marker infowindow to open when the corresponding link is clicked in the sidebar. My code is below:
var map;
var infowindow;
var image = [];
var gmarkers = [];
var place;
var side_bar_html = "";
image['attraction'] = 'http://google-maps-icons.googlecode.com/files/beach.png';
image['food'] = 'http://google-maps-icons.googlecode.com/files/restaurant.png';
image['hotel'] = 'http://google-maps-icons.googlecode.com/files/hotel.png';
image['city'] = 'http://google-maps-icons.googlecode.com/files/smallcity.png';
function mapInit(){
var placeLat = jQuery("#placelat").val();
var placeLng = jQuery("#placelng").val();
var centerCoord = new google.maps.LatLng(placeLat, placeLng);
var mapOptions = {
zoom: 15,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var yMaxLat = ne.lat();
var xMaxLng = ne.lng();
var yMinLat = sw.lat();
var xMinLng = sw.lng();
//alert("bounds changed");
updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng);
show("attraction");
show("food");
show("hotel");
show("city");
makeSidebar();
});
function updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng) {
jQuery.getJSON("/places", { "yMaxLat": yMaxLat, "xMaxLng": xMaxLng, "yMinLat": yMinLat, "xMinLng": xMinLng }, function(json) {
if (json.length > 0) {
for (i=0; i<json.length; i++) {
var place = json[i];
var category = json[i].tag;
var name = json[i].name;
addLocation(place,category,name);
//makeSidebar();
}
}
});
}
function addLocation(place,category,name) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(place.geom.y, place.geom.x),
map: map,
title: place.name,
icon: image[place.tag]
});
//var iwNode = document.getElementById("infowindow");
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<div id='infowindow'><div id='infowindow_name'><p>"+ place.name +"</p></div><div id='infowindow_contents'><p>" + place.tag +"</p><a href='/places/"+place.id+"' id='place_link'>Show more!</a></div></div>"
});
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
});
}
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
makeSidebar();
}
jQuery('#attractionbox').click(function() {
boxclick(this, 'attraction');
});
jQuery('#foodbox').click(function() {
boxclick(this, 'food');
});
jQuery('#hotelbox').click(function() {
boxclick(this, 'hotel');
});
jQuery('#citybox').click(function() {
boxclick(this, 'city');
});
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
function makeSidebar() {
//var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
side_bar_html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = side_bar_html;
}
}
jQuery(document).ready(function(){
mapInit();
//makeSidebar();
});
Any help would be much appreciated - what can I do to get the sidebar loaded when the page loads, and to get the link click event working? Thanks!
The reason your links are not working is that you are defining your my_click and makeSidebar functions inside of your mapInit function and so they are not available outside of the scope of mapInit. Simply move them outside of mapInit and everything should just work.
As for the load event ... what you are looking for is the addDomListener method of google.maps.event. Simply use
google.maps.event.addDomListener(window, 'load', name_of_your_inital_function);
// e. g. google.maps.event.addDomListener(window, 'load', mapInit);
Finally; notta bene ... don't do this:
var image = [];
image['attraction'] = 'data';
image['food'] = 'more data';
Arrays are not meant to be used as hashes in Javascript. Use objects for dictionaries / hashes instead -- it's what you are actually doing (Array "subclasses" Object) and it will make it easier for others to use your code (and save you from headaches down the line).
var image = {};
image['attraction'] = 'data';
image['food'] = 'more data';

Categories