I am new to JavaScript.
Writing a script that uses GooogleMaps API
Working OK. Get Lat Lngs from Database, Make markers, put on Map.
Decided to move a function call up a level, (it was in the OnSuccess method of a PageMethod call). Stopped working.
Put in alerts to diagnose. Starts working.
Narrowed down to having alert at top of called function MakeLatLngs().
MakeLatLngs code appears to execute regardless of alert being present or commented out.
It is just that the map displays with alert statement in and doesn't display with alert statement commented out.
The alert is just text and not using any variable. So I am at a loss to understand what is going on here.
The same thing is happening in the function that draws the map DrawMap(). I put an informative alert at the start of the function and the map draws. Leave it out and the map doesn't.
Any clues as to what is going on would be appreciated?
The script is below.
Flow starts at function Initialise at bottom of script.
thanks
var myPositions = [];
var myRoutes = [];
var myString = [];
var myLatLngs = [];
var myTitles = [];
var NumPoints;
var map;
var poly;
var RouteName;
var myMarkers = [];
var myMapCentre = new google.maps.LatLng(-41.2954168187213, 174.767133718655);
function DrawMap() {
alert("Generating Points for " + RouteName);// Need this to display
var thisLatLng = myLatLngs[0];
var myOptions = {
zoom: 8,
center: thisLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
MakeMarkers();
RouteLine();
}
function OnSuccess1(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
}
function OnError1(response) {
}
function Marker()
{
this.meterId=0;
this.latLng="";
}
function OnSuccess(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
alert("Numpoints is " + NumPoints);
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
alert("Exiting OnSuccess");
//MakeLatLngs(); //ORIGINAL POSITION OF LATLNG CALL
return true;
}
function setRoute() {
RouteName = prompt(' What route?', '');
}
function OnError(error) {
alert("In Error");
}
function RouteLine() {
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
var path = poly.getPath();
for (var i = 0; i < NumPoints; i++) {
path.push(myLatLngs[i]);
}
}
function MakeLatLngs() {
alert("You need me now " );//Got to have this to display OK when called from LoadData
myLatLngs = new Array();
for (var i = 0; i < NumPoints; i++) {
var sMarker = myPositions[i];
var SeqPos = sMarker.indexOf(";");
var latLngPos = sMarker.indexOf(";", SeqPos + 1);
var marker = sMarker.substring(0, latLngPos);
//alert("Marker is " + marker);
//var Seq = sMarker.substring(latLngPos + 1, SeqPos - latLngPos);
myTitles[i] = marker;
//alert("MeterId is " + marker);
var sLatLng = sMarker.substring(latLngPos + 1)
//alert("SLatLng is " + sLatLng);
var pos = sLatLng.indexOf(",");
//alert("pos is " + pos);
var sLat = sLatLng.substring(0, pos);
//alert("sLat is " + sLat);
var sLng = sLatLng.substring(pos + 1, sLatLng.length - 1);
//alert("sLng is " + sLng);
var lat = parseFloat(sLat);
var lng = parseFloat(sLng);
//alert("Lat is " + lat + " Long is " + lng);
if (!isNaN(lng) && !isNaN(lat) && lat != 0 && lng != 0 ) {
var latlng = new google.maps.LatLng(lat, lng);
myLatLngs[i] = latlng;
}
}
alert("Exiting MakeLatLngs")
}
function MakeMarkers() {
for (var i = 0; i < NumPoints; i++) {
var sTitle = "MyValue " + i;
var marker = new google.maps.Marker({
position: myLatLngs[i],
map: map,
title: myTitles[i]
});
}
}
function LoadData() {
setRoute();//Get the desired route from the user
PageMethods.GetMarkers(RouteName, OnSuccess, OnError);
MakeLatLngs(); //Works here ONLY WHEN AN ALERT IS FIRST LINE in FUNCTION. Orginal call was at end of OnSuccess
//PageMethods.GetRouteBoundaries(OnSuccess1, OnError1);
return false;
}
function initialize() {
LoadData();
DrawMap();
}
google.maps.event.addDomListener(window, 'load', initialize);//yes you do need this with or without <body onload="initialise">
The reason is that your PageMethods.GetMarkers is asynchronous, so the data hasn't loaded when you invoke DrawMap. I guess when you use the alert, it pauses execution long enough for the data to load. Put the DrawMap method inside the OnSuccess of the page method, and that should solve the problem.
Related
I am learning leaflet . My idea was to create map with clusters
, everything works but when I move map new markers keep
overlay old ones.I could see that every time i move map marker gets bolder, so i assume they overlay each other.
How to remove old ones ? I tried everything , cant figure out,
here is code:
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
var marker;
var clusters = {}; // key is lat/lon, value is a L.MarkerClusterGroup
var nodecounts = {};// key is lat/lon, value is the number of nodes at that location
var markers = {}; // key is plot id, value is an L.Marker
// Browsable map
function initMap(lat,lon,zoom){
// set up the AJAX stuff
ajaxRequest=GetXmlHttpObject();
if (ajaxRequest==null) { return; }
// set up the map
map = new L.Map('map');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 20, attribution: osmAttrib});
if (!lat) { lat=44.3008813; lon=-79.6114973; zoom=14; }
map.setView(new L.LatLng(lat,lon),zoom);
map.addLayer(osm);
askForPlots();
map.on('moveend', onMapMove);
}
function askForPlots() {
// request the marker info with AJAX for the current bounds
var bounds=map.getBounds();
var minll=bounds.getSouthWest();
var maxll=bounds.getNorthEast();
$("#regTitle").html("Hello World");
$("#listings").load('/engine/boxlistings.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat);
var msg='/engine/box.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat;
ajaxRequest.onreadystatechange = gotPlots;
ajaxRequest.open('GET', msg, true);
ajaxRequest.send(null);
}
function onMapMove(e) {
askForPlots();
}
function gotPlots() {
if (ajaxRequest.readyState!=4 || ajaxRequest.status!=200) return;
var resp = JSON.parse(ajaxRequest.responseText);//.replace(/[^\u000A\u0020-\u007E]/g, "")
var plotlist = resp.plots;
// First, tot up the number at each position, so we know whether to cluster
for (var i=0; i<plotlist.length; i++) {
var plot = plotlist[i];
if (markers[plot.id]) continue;
var ll = new L.LatLng(plot.lat,plot.lon, true);
var key= locationKey(ll);
nodecounts[key] = (nodecounts[key] || 0) + 1;
}
// Custom
var mapcluster = L.markerClusterGroup({ chunkedLoading: true,maxClusterRadius:60 });
for (var i = 0; i < plotlist.length; i++) {
var a = plotlist[i];
var title = a.name;
var marker = L.marker(L.latLng(a.lat, a.lon), {
icon: new L.DivIcon({
className: 'tooltips',
html: ''+
'<div class="triangle" id="'+a.id+'"><strong>'+a.price+'</strong></div>'
})
});
marker.bindPopup(title);
mapcluster.addLayer(marker);
}
map.addLayer(mapcluster);
console.log(mapcluster);
}
function locationKey(ll) { return ll.lat.toFixed(5)+","+ll.lng.toFixed(5); }
// Single plot map
// AJAX support
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); }
return null;
}
Any help appreciated
I use this function:
function removeMarkers() {
map.eachLayer(function (layer) {
layer.remove();
});
}
But it also removes the map so I follow with:
L.imageOverlay(imageUrl, imageBounds).addTo(map);
I am building an widget where user can upload an excel file and the places are get marked in the google map.
The following code works, but issue comes when i am reading an large excel file with 10k amount of data, the browser gets stuck. I am using a for loop and adding some timeout to get the data from the google api.
I pass the city name and get the latitude and longitude and mark it on the map.
Is there a better way i can implement?
Here is the code:
function googleMapsInit(widId, $scope, $http, $rootScope, $mdDialog) {
$scope.finish = function() {
var objIndex = getRootObjectById(widId, $rootScope.dashboard.widgets);
$mdDialog.hide();
document.getElementById('map').innerHTML = "";
//excel data
var array = JSON.parse($rootScope.json_string);
$scope.locationData = [];
//dividing it to chunks
var k,j,temparray,chunk = 8;
for (k=0,j=array.length; k<j; k+=chunk) {
temparray = array.slice(k,k+chunk);
var i;
//getting the longitude and latitude from the google geo api
for(i=0;i < temparray.length ; i++){
Geocode(temparray[i].PLACE_OF_ACCIDENT);
}
}
//sometimes data gets delayed
setTimeout(function(){ googleMap(); }, 5000);
};
function Geocode(address) {
var obj = {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
obj = {
lat : results[0].geometry.location.G,
lng : results[0].geometry.location.K
};
setTimeout(function(){ $scope.locationData.push(obj); }, 100);
}
else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else if (status === google.maps.GeocoderStatus.ZERO_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else {
}
});
}
function googleMap() {
var dataStore = $scope.locationData;
var array = JSON.parse($rootScope.json_string);
var map = new google.maps.Map(document.getElementById('map'),{
center: {lat: 7.85, lng: 80.65},
zoom: 6 });
var pinImageGreen = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/green-dot.png");
var pinImageBlue = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
var marker = [];
var k;
for(k=0; k < array.length; k++){
marker[k] = new google.maps.Marker({
position: {lat: $scope.locationData[k].lat, lng: $scope.locationData[k].lng},
map: map,
title: array[k].PLACE_OF_ACCIDENT,
icon: pinImageGreen,
VEHICLE_TYPE: array[k].VEHICLE_TYPE,
VEHICLE_USAGE: array[k].VEHICLE_USAGE,
VEHICLE_CLASS: array[k].VEHICLE_CLASS
});
marker[k].addListener('click', function(data) {
var j;
for(j=0;j<array.length;j++){
if(($scope.locationData[j].lat == data.latLng.G) && ($scope.locationData[j].lng == data.latLng.K )){
document.getElementById("details").innerHTML =
array[j].PLACE_OF_ACCIDENT + "</br>" +
array[j].VEHICLE_TYPE + "</br>" +
array[j].VEHICLE_USAGE + "</br>" +
array[j].VEHICLE_CLASS + "</br>" ;
}
}
});
}
}
$scope.cancel = function() {
$mdDialog.hide();
};
}
One way to slightly improve performance is this: Instead of adding markers to the map one at a time, just create the markers array separately and then add them all at once to the map. Here is a sample code:
var markersData = [];
for (var i = 0; i < myArray.length; i++) {
var item = scope.myArray[i];
if (item.lat != undefined && item.lon != undefined) {
var icon = 'icon.png';
markersData.push({
lat: item.lat,
lng: item.lon,
title: 'xyz'
});
}
}
map.addMarkers(markersData);
By the way I have used "gmaps.js" for this which simplifies coding google maps, but you don't necessarily need it. The general idea is to avoid adding markers to the map inside the loop, one by one.
I'm implementing google maps roads API to pick up the coordinates where I clicked on the roads. But it returns more than expected coordinates and placeids. Suppose I set a direction from place A to place B using directions API then I clicked some points (lets say 10 points) on the roads to draw the route. In response the roads API is returning more than 10 placeIds and coordinates where I need only 10. Here is the code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
//GOOGLE_API_KEY
var apiKey = '';
if(!apiKey)
alert("Please provide API Key");
var map;
var elevator;
var directionsDisplay;
var directionsService;
var placeDetailsService;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize()
{
document.getElementById("save").style.display="none";
var mapOptions = {
zoom: 17,
center: {lat: 40.69847032728747, lng: -73.9514422416687}
};
directionsService = new google.maps.DirectionsService();
var polylineOptionsActual = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 0.6,
strokeWeight: 2
});
directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: polylineOptionsActual});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
//Place Details
placeDetailsService= new google.maps.places.PlacesService(map);
// Create an ElevationService
elevator = new google.maps.ElevationService();
// Adds a Places search box. Searching for a place will center the map on that location
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
//Start Location Searchbox
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocStart'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function () {
var placeStart = autocomplete.getPlace();
//alert(placeStart.place_id);
placeDetailsService.getDetails({
placeId: placeStart.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place.geometry.location);
//alert("Start Location: "+place.geometry.location.G);
document.getElementById("startPlaceLat").value=place.geometry.location.G;
document.getElementById("startPlaceLng").value=place.geometry.location.K;
}
});
});
//End Location Searchbox
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('autocEnd'));
autocomplete1.bindTo('bounds', map);
autocomplete1.addListener('place_changed', function () {
var placeEnd = autocomplete1.getPlace();
//alert(placeEnd.place_id);
placeDetailsService.getDetails({
placeId: placeEnd.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place.geometry.location);
//alert("End Location: "+place.geometry.location.G);
document.getElementById("endPlaceLat").value=place.geometry.location.G;
document.getElementById("endPlaceLng").value=place.geometry.location.K;
}
});
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function (poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function (ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
document.getElementById("snappedCoordinatesArray").value = "";
document.getElementById("snappedPaceIdArray").value = "";
document.getElementById("altitudeArray").value = "";
document.getElementById("dataDisplay").style.display = "none";
document.getElementById("autocStart").value = "";
document.getElementById("autocEnd").value = "";
document.getElementById("startPlaceLat").value = "";
document.getElementById("startPlaceLng").value = "";
document.getElementById("endPlaceLat").value = "";
document.getElementById("endPlaceLng").value = "";
document.getElementById("save").style.display="none";
directionsDisplay.set('directions', null);
return false;
});
_init();
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function (data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
//getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data)
{
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++)
{
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
//getElevation(latlng);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
//get Altitude in meters
getElevation(snappedCoordinates);
document.getElementById("snappedCoordinatesArray").value = snappedCoordinates;
document.getElementById("snappedPaceIdArray").value = placeIdArray;
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function (speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
//passDataToObjC();
}
}
//Color of the roads depends upon speed limit
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
//Call Elevation API to get Altitude
function getElevation(snappedCoordinatesArr)
{
var locations = [];
// Retrieve the latlng and push it on the array
for (var i = 0; i < snappedCoordinatesArr.length; i++)
{
locations.push(snappedCoordinatesArr[i]);
}
// Create a LocationElevationRequest object using the array's one value
var positionalRequest =
{
'locations': locations
}
//alert(positionalRequest);
// Initiate the location request
elevator.getElevationForLocations(positionalRequest, function (results, status)
{
if (status == google.maps.ElevationStatus.OK)
{
// Retrieve the first result
if (results)
{
var altitudeArr = [];
for (var j = 0; j < results.length; j++)
{
altitudeArr.push(results[j].elevation);
}
document.getElementById("altitudeArray").value = altitudeArr;
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("save").style.display="block";
//alert(altitudeArr);
}
else
{
alert('No results found');
}
}
else
{
alert('Elevation service failed due to: ' + status);
}
});
}
//Call Directions API to draw route
function calcRoute()
{
var start = document.getElementById("autocStart").value;
var end = document.getElementById('autocEnd').value;
var selectedMode = document.getElementById("travelType").value;
//alert(start);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
//Save Details into Database
function _init()
{
document.getElementById("geodata-form").onsubmit = function (e) {
e.preventDefault();
var f = e.target,
formData = new FormData(f),
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.responseText) {
alert('Geodata successfully saved.');
document.getElementById("save").style.display="none";
// location.reload();
} else {
alert('Error occured !');
}
}
}
xhr.open("POST", f.action);
xhr.send(formData);
}
}
$(window).load(initialize);
</script>
I have created a JSfiddle here. Just give a google API key and then tell me whats wrong with this code?
You are calling the Roads API with interpolate: true. According to the documentation, that causes it to behave the way you say it is.
from the documentation:
interpolate — Whether to interpolate a path to include all points forming the full road-geometry. When true, additional interpolated points will also be returned, resulting in a path that smoothly follows the geometry of the road, even around corners and through tunnels. Interpolated paths will most likely contain more points than the original path. Defaults to false.
I'm having trouble getting my map to clear the clusters on a new search. Any ideas?
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
// clear #side_bar bottom text
document.getElementById("side_bar").innerHTML = "";
// clear .alertBox text
$('.alertBox').html('');
}
function searchLocationsNear(center) {
clearLocations();
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
downloadUrl(searchUrl, function (data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
if (markerNodes.length > 0) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var category = markerNodes[i].getAttribute("category");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
// createOption(name, distance, i);
createMarker(latlng, name, address, category);
bounds.extend(latlng);
}
map.fitBounds(bounds);
var markerclusterer = new MarkerClusterer(map, markers);
// markerclusterer.setMap(null);
makeSidebar();
} else {
$('.alertBox').html('Sorry, there are no jobs that are close to your location.');
}
});
}
You should try this :
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
markerclusterer.clearMarkers()
}
According to the docs the clusterer can be clear with clearMarkers() method.
UPDATE
Call clear only when we have already create the MarkerClusterer.
if(markerclusterer)
{
clearLocations();
}
I am trying to reference an array of markers that I created but when I try reference an array element the element receives the message GLOBAL_MARK.0 is null or not an object. I think it might be a scope issue but I'm not sure how to handle it. Here's the code.
var GLOBAL_MARK = "[]"
var vcount = 0;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
MyLat = "47.614495"
MyLng = "-122.341861"
map.setCenter(new GLatLng(MyLat, MyLng), 13);
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers [i].getAttribute("lng")));
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker)
map.addOverlay(marker);
}
});
OutTest()
}
}
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker
vcount = vcount + 1
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng)
}
function createMarker(point, name, address, type, id, date1, date2) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address + "<br><br><input type=\"button\" value=\" View Posts \" onclick=\"view_posts('" + id + "','" + type + "','" + date1 + "','" + date2 + "','no')\">"
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Lots of errors in this code. GLOBAL_MARK was definitely declared wrong to be used as an object like you use it in MyAddMarker(). I'll try to fix as many as I can see by eye without actually being able to run the code:
GLOBAL_MARK = [];
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker);
map.addOverlay(marker);
}
// when the code gets here, the data from allmarkers.php is done
});
OutTest();
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker;
vcount = vcount + 1;
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng);
}
In addition, I don't see a declaration for vcount anywhere.
And, I suspect you're calling OutTest() before the anonymous function in GDownloadUrl has completed. That very well may be an asynchronous function that hasn't completed yet when you call OutTest().