I am making a google maps for my website so you can view where each user is.
This works perfect only when you click on an icon of someone it will show you the same every time i cant understand it am i doing something wrong?
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","includes/xml.php",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("USER");
var infoWindow = new google.maps.InfoWindow();
var map;
var users = [];
function initialize() {
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(52.1424, 5.09428),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i=0;i<x.length;i++) {
var id = x[i].getElementsByTagName("USERID")[0].childNodes[0].nodeValue;
users['USERNAME'+id] = x[i].getElementsByTagName("USERNAME")[0].childNodes[0].nodeValue;
users['CITY'+id] = x[i].getElementsByTagName("CITY")[0].childNodes[0].nodeValue;
users['COUNTRY'+id] = x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
users['IMAGE'+id] = x[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue;
users['IMAGEPIN'+id] = x[i].getElementsByTagName("IMAGEPIN")[0].childNodes[0].nodeValue;
users['LAT'+id] = x[i].getElementsByTagName("LAT")[0].childNodes[0].nodeValue;
users['LONG'+id] = x[i].getElementsByTagName("LONG")[0].childNodes[0].nodeValue;
users['DATETIME'+id] = x[i].getElementsByTagName("DATETIME")[0].childNodes[0].nodeValue;
users['TWITTER'+id] = x[i].getElementsByTagName("TWITTER")[0].childNodes[0].nodeValue;
users['FA'+id] = x[i].getElementsByTagName("FA")[0].childNodes[0].nodeValue;
users['ACTIVEUSER'+id] = x[i].getElementsByTagName("ACTIVEUSER")[0].childNodes[0].nodeValue;
users['myLatlng'+id] = new google.maps.LatLng(users['LAT'+id],users['LONG'+id]);
users['content'+id] = '<div style="width:220px;"><img id="avatar"style="margin-right: 5px;" src="' + users['IMAGE'+id] + '"></img>' +
'<b>' + users['USERNAME'+id] + '</b><br />' +
users['CITY'+id] + '<br />' + users['COUNTRY'+id] + '<br />' +
'<i>' + users['DATETIME'+id] + '</i><br />' +
'<img src="http://www.kinzart.com/images/fur-affinity-icon.png" Alt="Twitter" width="30" height="30">' +
'<img src="http://biophiliccities.org/wp-content/uploads/2013/06/twitterICON.png" Alt="Twitter" width="30" height="30">';
users['window'+id] = new google.maps.InfoWindow({ content: users['content'+id]});
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
google.maps.event.addListener(users['marker'+id], 'click', function() { infoWindow.setContent(users['content'+id]); infoWindow.open(map, users['marker'+id]) });
}
}
google.maps.event.addDomListener(window, 'load', initialize);
The problem is that when you setup your event listener within the loop, it ends up that every iteration of the loop sets the infowindow content to be whatever the last value of users['content'+id] is. You need to look into using closures in your code.
Here's another way of doing it that should work:
for (i=0;i<x.length;i++) {
... // trimmed for brevity
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
bindInfoWindow(users['marker'+id], users['content'+id]);
}
then have this function:
function bindInfoWindow(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(content);
infoWindow.open(map, marker)
});
}
Related
I have a google map which loads results on page load which is fine but I have an ajax search form which updates the results by ajax in a separate div but it doesn't update the map. I am trying to figure out how to update the map when the ajax call is completed but I am stuck. Any help would be greatly appreciated!
Here is the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
$(document).ready(function() {
var markersInfo = $('.ia-card').map(function() {
var info = {
id: $(this).data('map-id'),
address: $(this).data('map-address'),
title: $(this).data('map-title'),
price: $(this).data('map-price'),
latitude: $(this).data('map-latitude'),
longitude: $(this).data('map-longitude'),
html: "<img src=" + $(this).data('map-image') + ">",
link: $(this).data("map-link"),
contentHtml: "<div class='image'>" + "<img src=" + $(this).data('map-image') + ">" + "</div>" + '<b>' + $(this).data('map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).data('map-price') + "</div>" + "<br><a href='" + $(this).data("map-link") + "'>More>></a>"
};
return info;
}).get();
var distinctMarkerInfo = [];
markersInfo.forEach(function(item) {
if (!distinctMarkerInfo.some(function(distinct) {
return distinct.id == item.id;
})) distinctMarkerInfo.push(item);
});
initGoogleMap(distinctMarkerInfo);
// GMAP ON SEARCH RESULTS PAGE
function initGoogleMap(markersInfo) {
var mapOptions = {
// zoom: 2,
// center: new google.maps.LatLng(53.334430, -7.736673)
},
bounds = new google.maps.LatLngBounds(),
mapElement = document.getElementById('stm_map_results'),
map = new google.maps.Map(mapElement, mapOptions);
markerList = []; // create an array to hold the markers
var geocoder = new google.maps.Geocoder();
var iconBase = '../assets/images/';
$.each(markersInfo, function(key, val) {
var marker = new google.maps.Marker({
//map: map,
position: {lat: parseFloat(val.latitude), lng: parseFloat(val.longitude)},
title: val.title,
icon: iconBase + 'single.png',
info: new google.maps.InfoWindow({
content: val.contentHtml
})
});
markerList.push(marker); // add the marker to the list
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
loc = new google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(loc);
});
map.fitBounds(bounds);
map.panToBounds(bounds);
var markerCluster = new MarkerClusterer(map, markerList, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
};
});
</script>
<div id="stm_map_results" style="width:100%; height:600px;"></div>
Since you are displaying markers via MarkerClusterer i would propose the following solution to update the map.
once the data is retrieved, clear the existing markets from map using
MarkerCluster.clearMarkers function
initialize a MarkerCluster with a new data
The below example demonstrates how to "refresh" markers on the map:
function placeMarkers(data){
var markers = data.map(function (item, i) {
return new google.maps.Marker({
position: { lat: item.lat, lng: item.lng }
});
});
//1.clear existing markers
if (markerCluster)
markerCluster.clearMarkers();
//2.init marker cluster
markerCluster = new MarkerClusterer(map, markers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
}
Demo
Here is the map I am working on. I'm trying to have only one infowindow open at a time, and the open infowindow will close when the map or another marker is clicked.
I know this has been asked and answered several times already, but I've attempted to go through those examples and can't figure out how to apply them to my specific code, which pulls photos from Flickr and puts them in infowindows tied to markers. I'm pretty sure the solution involves creating a single infowindow and changing its content.
updated fiddle displaying issue
code snippet (from fiddle):
var lat = 0;
var long = 0;
$(document).ready(function() {
$.getJSON("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=14fca78b18f8e8f4d22216494ea29abf&user_id=136688117%40N05&has_geo=1&extras=geo&format=json&jsoncallback=?", displayImages3);
function displayImages3(data) {
$.each(data.photos.photo, function(i, item) {
lat = item.latitude;
lng = item.longitude;
var photoURL = 'https://farm' + item.farm + '.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
var linkURL = 'https://www.flickr.com/photos/' + item.owner + '/' + item.id + '';
htmlString = '<img src="' + photoURL + '">';
var contentString = '<div id="content">' + htmlString + '</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var myLatlngMarker = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatlngMarker,
map: myMap
});
marker.setIcon('https://www.sherrihill.com/static/skin/images/pinkdot_pink-dot.png');
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(myMap, marker);
});
});
}
});
var myLatlngCenter = new google.maps.LatLng(46.140743, -116.682910);
var mapOptions = {
center: myLatlngCenter,
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<title>Cascadia Panamericana</title>
<div id="map_canvas"></div>
Make a single infowindow in the global scope. Re-use it to display the content for each marker. In this example I add the HTML content for the infowindow as a property of the marker, then access it in the marker click event listener with this.htmlContent.
var contentString = '<div id="content">' + htmlString + '</div>';
var myLatlngMarker = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatlngMarker,
map: myMap,
icon: 'https://www.sherrihill.com/static/skin/images/pinkdot_pink-dot.png',
htmlContent: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.htmlContent);
infowindow.open(myMap, this);
});
working code snippet:
var lat = 0;
var long = 0;
var infowindow = new google.maps.InfoWindow({});
$(document).ready(function() {
$.getJSON("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=14fca78b18f8e8f4d22216494ea29abf&user_id=136688117%40N05&has_geo=1&extras=geo&format=json&jsoncallback=?", displayImages3);
function displayImages3(data) {
$.each(data.photos.photo, function(i, item) {
lat = item.latitude;
lng = item.longitude;
var photoURL = 'https://farm' + item.farm + '.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
var linkURL = 'https://www.flickr.com/photos/' + item.owner + '/' + item.id + '';
htmlString = '<img src="' + photoURL + '">';
var contentString = '<div id="content">' + htmlString + '</div>';
var myLatlngMarker = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatlngMarker,
map: myMap,
icon: 'https://www.sherrihill.com/static/skin/images/pinkdot_pink-dot.png',
htmlContent: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.htmlContent);
infowindow.open(myMap, this);
});
});
}
});
var myLatlngCenter = new google.maps.LatLng(46.140743, -116.682910);
var mapOptions = {
center: myLatlngCenter,
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<title>Cascadia Panamericana</title>
<div id="map_canvas"></div>
When using google maps api v3, I add a marker to the map with an infowindow with html content and a link w/custom class. I want a jquery trigger to execute upon clicking the link custom class but i've tried many different ways and nothing is working..
Here is my code:
function addMarker(mapArray) {
var techs = mapArray.techs;
var techlinks = mapArray.technamelink;
var address = mapArray.address;
var starttime = mapArray.starttime;
var endtime = mapArray.endtime;
var id = mapArray.id;
var lat = mapArray.lat;
var lng = mapArray.lng;
var client = mapArray.client;
var project = mapArray.project;
var title = techlinks + "<br /> <a class='addresszoom' data-lat='" + lat + "' data-lng='" + lng + "' style='cursor: pointer; font-weight: normal; color: black;'>" + client + "<br />" + starttime + " - " + endtime + "<br />" + address + "</a>";
marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: map, title: techs });
marker.id = id;
markersArray.push(marker);
bounds.extend(marker.position);
addInfoWindow(marker, title);
}
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
map.panTo(marker.position);
});
google.maps.event.addListener(map, 'click', function () {
infoWindow.close();
});
}
jquery:
$(".addresszoom").click(function() {
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
alert('it worked');
map.setCenter(new google.maps.LatLng(lat, lng));
map.setZoom(12);
});
What you want to do is creating a click event handler on a dynamically created element.
Try this :
$(document).on("click", ".addresszoom", function() {
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
alert('it worked');
map.setCenter(new google.maps.LatLng(lat, lng));
map.setZoom(12);
});
Documentation
Hi in my google map i just draw a one marker when map loads.But then map is zoomed fully in which is really confusing. but when i draw more than one markers map is centered properly and zoomed to a certain level. how can it overcome this.
i have got a loop inside my draw markers function and in that i get only one object that has coordinates. when i get more than one objects from 'markers' map is centered properly. but when it has a only one object to loop. markers gets drawn but map is not well centered and zoomed(zoomed in fully)
function drawMarkers(markerList) {
debugger;
var mapOptions = {
center: new google.maps.LatLng(-24.504710, 134.039231),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var currentLocation;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
//if (markerList[i].Longitude > 0) {
var data = markerList[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.DriverName,
});
var driverCurrentLocation = document.getElementById('<%= hdfDriverCurrentLocation.ClientID %>').value;
latlngbounds.extend(marker.position);
//if (markerList[i].Longitude > 0) {
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
debugger;
var lat = data.Latitude;
var lng = data.Longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
currentLocation = results[1].formatted_address;
}
infoWindow.setContent('<div style="overflow: auto;width: 275px;">' +
'<div id="leftSideMainDiv" class="col25" style="padding-Left:0px; width:22%;">' +
'<div class="col100"><img src="../Images/DriverImages/driver_icon.jpg" height="60" width="60"/></div>' +
'</div>' +
'<div id="RightSideMainDiv" class="col75" style="width:72%;">' +
'<div class="col100" style="font-weight:bold; padding-top:0px; padding-left:0px; font-size:smaller;"> ' + data.DriverName + '</div>' +
'<div style="font-size:smaller; padding-top:15px;">Job Number :' + data.JobId + ' - ' + data.JobType + '</div>' +
'<div style="font-size:smaller;">Delivery Address :' + data.DeliveryAddress + '</div>' +
'<div style="font-size:smaller;">Current Location :' + currentLocation + '</div>' +
'<div style="font-size:smaller;">Last Update :' + data.LastUpdatedTime + '</div>' +
'</div>');
infoWindow.open(map, marker);
}
});
});
})(marker, data);
//}
}
//}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
}
Related question: How to set zoom level in google map
If you only have one marker (markers.length == 1), then don't call map.fitBounds(). Change:
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
To:
map.setCenter(latlngbounds.getCenter());
if (marker.length != 1) map.fitBounds(latlngbounds);
map.setZoom(5);
on the initialization of maps set the zoom level, Here the zoom is set to 5
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
Add the map variable outside of map's function scope
var map;
and then modify the line inside your map function-
map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
then after calling your map function drawMarkers(markerList) you need to set the zoom as-
$(document).ready(function(){
drawMarkers(markerList)
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
});
Let me know if that works!
Here in this small code snippet,I am facing a little problem.THe problem is if I close all the marker after page completely loaded.And again when I click on markers same detail display on all markers..Here is my code:
var map, infoBubble;
function onload() {
var mapCenter = new google.maps.LatLng(13.0162476, 77.5073893);
map = new google.maps.Map(document.getElementById('dvMap'), {
zoom: 8,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (i = 0; i < markers.length; i++) {
//icons[i];
//alert("undefined icons" + icons[i]);
var data = markers[i]
//var myLatlng = new google.maps.LatLng(13.4162691, 77.5064153);
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Par Id ' + data.ParId,
icon: 'Google Marker/In/' + data.title + '.png'
});
if (data.RANK == "1") {
data.RANK = "Primary";
} else {
data.RANK = "Secondary";
}
// alert(data.IMAGEPATH);
var contentString = '<div id="content" align="left" >' +
'<h1>Parcel Details</h1>' +
'<h3>Parcel Id:' + data.ParId + '</h3>' +
'<h3>Rank:' + data.RANK + '</h3>' +
'<h3>Captured by:' + data.Capturedby + '</h3>' +
'<h3>Captured Date:' + data.Capturedate + '</h3>' +
'</div>';
infoBubble = new InfoBubble({
maxWidth: 300,
maxHeight: 200,
backgroundColor: 'rgb(236,255,255)'
});
infoBubble.open(map, marker);
var div = document.createElement('DIV');
div.align = "left";
div.innerHTML = '<IMG BORDER="0" ALIGN="Left" width=97% height=200px alt="Pulpit rock1" SRC="' + data.IMAGEPATH + '"/>';
infoBubble.addTab('Photo', div);
infoBubble.addTab('Details', contentString);
(function (marker, data) {
google.maps.event.addListener(marker, 'click', function () {
// if (!infoBubble.isOpen()) {
infoBubble.open(map, marker);
alert("Par Id:" + data.ParId);
//alert("2");
//}
//infoWindow.open(map);
});
// alert(data.title);
//google.maps.event.trigger(marker, 'click'); //stil
}(marker, data));
}
}
google.maps.event.addDomListener(window, 'load', onload);
the infoBubble-variable will be overwritten inside the loop.
Solution: pass the infoBubble as argument to the function that adds the click-listener:
(function (marker, data , infoBubble) {
google.maps.event.addListener(marker, 'click', function () {
infoBubble.open(map, marker);
});
}(marker, data, infoBubble));