How to use MarkerCluster with geolocations from a database, displaying markers on the map works fine. but I haven't been able to implement marker clustering.
Any help would be appreciated
var customLabel = {residential: {label: 'R'},commercial: {label: 'C'},both: {label: 'B'}};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(43.6191,-113.9772),
zoom: 8
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl('URL/xml.php', function(data) {
var xml = data.responseXML;
var xmlmarker = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(xmlmarker, function(markerElem) {
var type = markerElem.getAttribute('service');
var address = markerElem.getAttribute('address');
var icon = customLabel[type] || {};
var markers = [];
var markerCluster = new MarkerClusterer(map, markers);
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
var locations = results[0].geometry.location;
var marker = new google.maps.Marker({ position: locations, label: icon.label });
markers.push(marker);
markerCluster.addMarker(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);
}
You are creating a new MarkerCluster every time you create a marker. Create it once, add all the markers to the same MarkerClusterer object.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(43.6191, -113.9772),
zoom: 8
});
var infoWindow = new google.maps.InfoWindow;
// ********************************************************************************
// ** move the markers array and the marker clusterer here, outside of the loop. **
// ********************************************************************************
var markers = [];
var markerCluster = new MarkerClusterer(map, [], {
imagePath: "https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m"
});
downloadUrl('http://map.northwestdatacom.com/xml.php', function(data) {
var xml = data.responseXML;
var xmlmarker = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(xmlmarker, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var phone = markerElem.getAttribute('phone');
var email = markerElem.getAttribute('email');
var host = markerElem.getAttribute('host');
var type = markerElem.getAttribute('service');
var address = markerElem.getAttribute('address');
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name;
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address;
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
var locations = results[0].geometry.location;
var marker = new google.maps.Marker({
position: locations,
label: icon.label
});
markers.push(marker);
markerCluster.addMarker(marker);
})
});
});
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<script>
var customLabel = {
residential: {
label: 'R'
},
commercial: {
label: 'C'
},
both: {
label: 'B'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(43.6191, -113.9772),
zoom: 6
});
var infoWindow = new google.maps.InfoWindow;
var markers = [];
var markerCluster = new MarkerClusterer(map, [], {
imagePath: "https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m"
});
// downloadUrl('http://map.northwestdatacom.com/xml.php', function(data) {
var xml = parseXml(xmlStr); // data.responseXML;
var xmlmarker = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(xmlmarker, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var phone = markerElem.getAttribute('phone');
var email = markerElem.getAttribute('email');
var host = markerElem.getAttribute('host');
var type = markerElem.getAttribute('service');
var address = markerElem.getAttribute('address');
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name;
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address;
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
var locations = results[0].geometry.location;
var marker = new google.maps.Marker({
position: locations,
label: icon.label
});
markers.push(marker);
markerCluster.addMarker(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 doNothing() {}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('MicrosoftXMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
};
google.maps.event.addDomListener(window, "load", initMap);
var xmlStr = '<markers><marker id="91" name="marcos centeno" phone="2083128603" email="marcoscenteno89#gmail.com" address="16111 17th st Heyburn 83336" service="residential" host=""/><marker id="90" name="Nathan Rasmussen" phone="123" email="nathan#truckmaster.com" address="290 west 125 south Idaho falls 83404" service="residential" host=""/><marker id="87" name="LIZ SANZON" phone="4564352410" email="lizeth.sanzon#dynamitewireless.com" address="20491 N Main ST, CAREY 83320" service="residential" host=""/><marker id="88" name="Liz Sanzon" phone="9674546465" email="lizeth.sanzon#dynamitewireless.com" address="244700 Ustick Rd, Wilder 83676" service="commercial" host=""/><marker id="89" name="Lizeth Sanzon" phone="4564352410" email="lizeth.sanzon#dynamitewireless.com" address=" 5870 Rock River Lane Kuna 83634" service="residential" host=""/><marker id="78" name="Ryan Rustici" phone="2087052118" email="ryan.rustici#gmail.com" address="11324 Interlaaken Dr SW Lakewood 98498" service="both" host=""/><marker id="86" name="Liz San" phone="31546304501" email="lizeth.sanzon#dynamitewireless.com" address="283 n 2600 e Roberts ID" service="residential" host=""/><marker id="77" name="Ryan Rustici" phone="2085551212" email="ryan#aol.com" address="4035 Ross Ave Ammon 83406" service="residential" host=""/><marker id="84" name="Marcos Centeno" phone="2083128603" email="marcoscenteno89#gmail.com" address="785 Garfield Ave, 10 Idaho Falls 83401" service="residential" host=""/><marker id="85" name="Marcos Centeno" phone="2083128603" email="mc172000#yaho.com" address="785 Garfield Ave, 10 Idaho Falls 83401" service="residential" host="199-33-218-234.cpe.safelink.net"/></markers>';
</script>
<script src="https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/src/markerclusterer.js"></script>
Related
I created a script where it will get lat and lon from sql and place a marker on the google map embedded, And I want to run the script every second like is auto getting data and place marker automatically.
<script>
var infoWindow= null;
var map = null;
var markersArray = [];
function initMap() {
var myLatlng = new google.maps.LatLng(14.657971, 120.976970);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
center: myLatlng,
zoom: 16,
streetViewControl : false,
mapTypeId : google.maps.MapTypeId.HYBRID,
});
var infoWindow = new google.maps.InfoWindow;
updateMaps();
function updateMaps() {
// Change this depending on the name of your PHP or XML file
downloadUrl('phpsqlajax_genxml.php?t=', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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 doNothing() {}
}
window.setInterval(updateMaps, 1000);
</script>
var update;
function updateInterval() {
update = setInterval(function() {
updateMaps()
}, 1000);
}
updateInterval();
You have to use JQuery to load updateInterval() when the document is ready or write <script>updateInterval();</script> at the end of the body.
I have just loaded the following code into my webpage and after many hours of troubleshooting, I can't get the Markers to show up?
I have confirmed that the parsing php file is working.
Javascript:
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var customIcons = {
accom: {
icon: 'images/google_map_icon_green.png'
},
food: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(
<?php if ($_COOKIE[company] == 'ch') { echo $ch[hls_lat].", ".$ch[hls_long]; } elseif ($_COOKIE[company] == 'shc') { echo $shc[hls_lat].", ".$shc[hls_long]; } elseif ($_COOKIE[company] == 'lmh') { echo $lmh[hls_lat].", ".$lmh[hls_long]; }?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow;
downloadUrl("required/xml_parse.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
SetMap: map_canvas,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map_canvas, infoWindow, html);
}
});
function bindInfoWindow(marker, map_canvas, 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 doNothing() {}
</script>
HTML:
<br />
<div class="inner-article-header"><h2>Map of Locations</h2></div>
<div id="map_canvas" style="height:565px; width:754px; margin:2px;"></div>
</div>
This is incorrect:
SetMap: map_canvas,
Should be (see MarkerOptions in the documentation):
map: map,
corrected marker constructor:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
Add the parsing of the XML into the initialize function, so map is valid when you add the markers:
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(0,0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
downloadUrl("example.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].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
working example (using one of my existing xml files, since you didn't provide any example data)
You have additional problems with the call to bindInfoWindow and its definition (map_canvas, should be map)
I have a set of markers, and when clicked on a marker there is a button that gets directions. The problem is that it only gives directions to the last loaded marker from the xml, not to each marker individually. Here is my code, maybe someone can tell what I'm doing wrong. Thank you.
UPDATE: WORKING CODE, QUESTION ANSWERED
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
function loadGoogleMap(){
// load google map
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=MyMap';
document.body.appendChild(script);
}
var map = ''
function MyMap(){
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var im = //user location icon
var CustomMarker = //marker icon location
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(locate, noPos());
} else {
noPos();
}
function locate(position){
myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var userMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: im
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
var address = markers[i].getAttribute("address");
var dt1 = markers[i].getAttribute("date1");
var dt2 = markers[i].getAttribute("date2");
var dt3 = markers[i].getAttribute("date3");
var tm1 = markers[i].getAttribute("time1");
var tm2 = markers[i].getAttribute("time2");
var tm3 = markers[i].getAttribute("time3");
var pid = markers[i].getAttribute("PID");
var DirLat = markers[i].getAttribute("lat");
var DirLng = markers[i].getAttribute("lng");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
//move up the creation of point
point = new google.maps.LatLng(
DirLat,
DirLng);
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
var content = "<button onclick='getDir();'>Get Directions</button>";
var jshtml = "<button onclick='raw();'>More Info</button>"; //an href function that redirects
var html = "<b>" + name + " " + content+ ' ' + jshtml+ "</b> <br/>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
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, html);
center: position;
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
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() {}
}
function noPos(error){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(41.850033, -87.6500523),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
var address = markers[i].getAttribute("address");
var dt1 = markers[i].getAttribute("date1");
var dt2 = markers[i].getAttribute("date2");
var dt3 = markers[i].getAttribute("date3");
var tm1 = markers[i].getAttribute("time1");
var tm2 = markers[i].getAttribute("time2");
var tm3 = markers[i].getAttribute("time3");
var pid = markers[i].getAttribute("PID");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
var jshtml = "<button onclick='raw();'>More Info</button>";;
var html = "<b>" + name + ' ' + jshtml + "</b>" + "<br>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
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, html);
position = marker.position;
center: position;
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
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 doNothing() {}
}
}
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
//LatLng created based on the passed arguments
var end = point;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
I globally defined every variable necessary for directions:
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
created a button for the function, and set in content which is visible in the infowindow:
var content = "<button onclick='getDir();'>Get Directions</button>";
Next I created hidden input fields in the map page, and assigned values of Latitude and Longitude of the markers that are clicked.
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
The directions function getDir pulls these values for the destination, myLatLng is the current location of the user:
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
var LatDir = document.getElementById('iLat').value;
var LngDir = document.getElementById('iLng').value;
var end = new google.maps.LatLng(LatDir,LngDir);
var request = {
origin:myLatLng,
destination:new google.maps.LatLng(LatDir,LngDir),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
For the full code, see the updated question's code.
I am working on a project and it is almost completed. The problem is that I am pretty new to Javascript and can't figure out how to do something that is probably pretty simple. Here is part of my code:
var dista;
var p;
var addrbounds;
var addrlat;
var addrlng;
var addr;
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var address = document.myform.customer.value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var addrbounds = results[0].geometry.location; //get geocoded results into variable
var addrlat = results[0].geometry.location.lat();
var addrlng = results[0].geometry.location.lng();
var p = new google.maps.LatLng(addrlat, addrlng);
var pt1 = new google.maps.LatLng(lat, lng);
dista = pt1.distanceFrom(p); //calculate distance between the points
var di = (dista/1000);
document.myform1.memory.value = di; //add dist to memory text box
return;
} else {
alert(address + ' not found');
}
});
// desired spot for if statement regarding distance
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
Basically what it does is that the first thing that happens in the addMarker() function is geocode an address and then calculate the distance away from the address. That works just fine. The problem comes when wanting to get the get the distance out the geocoder to create an if statement to only add markers from the database if it is within a certain radius. As you can see, I try to move it to a text box. That seems to work but it is part of a loop and won't update with each running of the loop.
I have been stuck for a couple days so any help would be appreciated. I hate being so close to finished but stuck!
Edit:
I got it to work. This is how I did it:
var dista;
var p;
var addrbounds;
var addrlat;
var addrlng;
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var address = document.myform.customer.value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var addrbounds = results[0].geometry.location;
var addrlat = results[0].geometry.location.lat();
var addrlng = results[0].geometry.location.lng();
var p = new google.maps.LatLng(addrlat, addrlng);
var pt1 = new google.maps.LatLng(lat, lng);
dista = pt1.distanceFrom(p);
var di = (dista/1000);
document.myform1.memory.value = di;
document.myform1.memory1.value = addrlat;
document.myform1.memory2.value = addrlng;
return;
} else {
alert(address + ' not found');
}
});
var tstlat = document.myform1.memory1.value;
var tstlng = document.myform1.memory2.value;
var tstpt = new google.maps.LatLng(tstlat, tstlng);
var pt = new google.maps.LatLng(lat, lng);
var distan = pt.distanceFrom(tstpt);
var tstdistance = (distan/1000);
if (tstdistance < 20){
// alert (tstdistance);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
else
{
return;
}}
Now I just need to fix a map refresh issue and then the project is complete!
You cannot get anything out of a geocoder-callback, geocoding forces an asynchronous request, you'll never know from outside the callback, when the response arrives.
Instead of getting something from outside, you must push something to outside from the callback(as you've done it already by setting the value of the textbox). You can also call another function from the callback and supply the distance as argument.
I am scratching my head for google map integration please help me out.
I want multiple markers, but its taking only 11 markers not more than that.
Below is my code..
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1");</script>
<script type="text/javascript"> google.load("maps", "3", {other_params:"sensor=false"});</script>
<script type="text/javascript">
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = "Charleston, SC";
locations[1] = "Tuscon, AZ";
locations[2] = "Phoenix, AZ";
locations[3] = "San Diego, CA";
locations[4] = "Los Angeles, CA";
locations[5] = "Aliso Viejo, CA";
locations[6] = "Laguna Beach, CA";
locations[7] = "Coto de Caza, CA";
locations[8] = "Philadelphia, PA";
locations[9] = "Ladera Ranch, CA";
locations[10] = "Thousand Oaks, CA";
var image = new google.maps.MarkerImage(
'../images/marker.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
geocoder.geocode( { 'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location
});
markers.push(marker);
alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,marker);
});
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
You can see practical example in: http://projects.pronixtech.net/kindcampaign/kind-country/
I think the problem is in "geocoder.geocode".
Look this code, with LatLong it works.
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = new google.maps.LatLng(10.32522, 10.07002);
locations[1] = new google.maps.LatLng(20.32522, 10.07002);
locations[2] = new google.maps.LatLng(30.32522, 10.07002);
locations[3] = new google.maps.LatLng(10.32522, 20.07002);
locations[4] = new google.maps.LatLng(20.32522, 20.07002);
locations[5] = new google.maps.LatLng(30.32522, 20.07002);
locations[6] = new google.maps.LatLng(10.32522, 30.07002);
locations[7] = new google.maps.LatLng(20.32522, 30.07002);
locations[8] = new google.maps.LatLng(30.32522, 30.07002);
locations[9] = new google.maps.LatLng(10.32522, 40.07002);
locations[10] = new google.maps.LatLng(20.32522, 40.07002);
locations[11] = new google.maps.LatLng(30.32522, 40.07002);
locations[12] = new google.maps.LatLng(10.32522, 50.07002);
locations[13] = new google.maps.LatLng(20.32522, 50.07002);
locations[14] = new google.maps.LatLng(30.32522, 50.07002);
locations[15] = new google.maps.LatLng(10.32522, 60.07002);
locations[16] = new google.maps.LatLng(20.32522, 60.07002);
locations[17] = new google.maps.LatLng(30.32522, 60.07002);
var image = new google.maps.MarkerImage(
'http://www.bookyourparis.com/images-site/beachflag.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
//geocoder.geocode( { 'address': location}, function(results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: location//results[0].geometry.location
});
markers.push(marker);
//alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,this);
});
//}
//});
}
google.maps.event.addDomListener(window, 'load', init);