Marker on all of polyline from Google maps directions V3 - javascript

Hello I have a question.
I draw a polyline and set markers on every point of the polyline. But my code doesn't set markers every point. Like the picture below, markers are just on some parts of polyline.
How can I set markers on every polyline?
function initMap() {
var markerArray = [];
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a map and center it on Manhattan.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 32.224759, lng: 60.298827},
});
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Retrieve the start and end locations and create a DirectionsRequest using
// DRIVING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#0000FF',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (var i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (var j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (var k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
var marker = markerArray[k] = markerArray[k] || new google.maps.Marker;
marker.setPosition(nextSegment[k]);
bounds.extend(nextSegment[k]);
marker.setMap(map);
}
}
}
polyline.setMap(map);
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById('total').innerHTML = total + ' km';
}

I think that I found your mistake which is in this piece of code:
for (var i = 0; i < legs.length; i++) {
...
for (var j = 0; j < steps.length; j++) {
...
for (var k = 0; k < nextSegment.length; k++) {
...
// Here you add the marker to the array if there is no marker set yet
var marker = markerArray[k] = markerArray[k] || new google.maps.Marker;
...
}
}
}
The mistake you did is, that you just look at the array's index k. However, the value of k is reset to 0 every time the for-loop starts again. Therefore, you have to add the array's length to the index:
for (var i = 0; i < legs.length; i++) {
...
for (var j = 0; j < steps.length; j++) {
...
for (var k = 0; k < nextSegment.length; k++) {
...
// This is the real index you want to look at
var marker = markerArray[markerArray.length + k] = markerArray[markerArray.length + k] || new google.maps.Marker;
...
}
}
}
However, I think that actually this reaches out and makes your code also lighter and more readable:
for (var i = 0; i < legs.length; i++) {
...
for (var j = 0; j < steps.length; j++) {
...
for (var k = 0; k < nextSegment.length; k++) {
...
// This looks much easier IMHO
var marker = new google.maps.Marker;
...
markerArray.push(marker);
}
}
}

Related

Markers remove when no more value is sent to the specific markers

Hi everyine please help me, I am trying to do a search filter on my vehicle tracking, the flow is, the servlet queries all data when there is no parameter filter is being sent by ajax. for example, I do have 5 data on query result so there will be 5 markers on the map, the ajax runs every two seconds so when I request a parameter for example only this spesific vehicle would be shown the query result would only be one, supposedly only marker on the screen, but the previous markers are not vanishing and keep up on the screen. how can I reset the markers into 0? can anyone please help me thanks! here is my code
<script type="text/javascript">
var values = [];
var map;
var markers = [];
function initMap()
{
var options = {
center: {lat: -33.890542, lng: 151.274856},
zoom: 4
};
map = new google.maps.Map(document.getElementById('map'), options);
var count = 0;
setInterval(function() {
getGps();
for(var i = 0; i <= markers.length; i++){
markers[i].setPosition(new google.maps.LatLng(values[count][1],values[count][2]));
count++;
}
}, 2000);
}
function removeMarkers(){
for(var i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[];
}
function getGps() {
xmlhttp.onreadystatechange=function() {
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
removeMarkers();
var res = xmlhttp.responseText;
console.log(res);
var split1 = res.split("|");
if(split1[0] != "NOK"){
for(var i = 0; i < split1.length; i++){
var split2 = split1[i].split(",");
String(split2);
var holder1 = holder = [split2[0],split2[1],split2[2]];
values.push(holder1);;
var marker1 = marker = new google.maps.Marker({map: map, icon: 'images/mapvehicle.png', draggable: true});
markers.push(marker1);
}
}
}
};
xmlhttp.open("POST","GpsPost",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("txtTerminal="+document.getElementById('txtTerminal').value+"&txtMerchant="+document.getElementById('txtMerchant').value+"&txtAccount="+document.getElementById('txtAccount').value);
}
add this function and call it after this line .
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
function removeMarkers(){
for(i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[]
values=[]
}

Google distancematrixservice response.rows[i].elements.status is zero_results but variable undefined

I'm using the example code from Google API for distance matrix Service. I want to catch the ZERO_RESULTS return, but if I'm trying to check response.rows[i].elements.status, but the console.log() says it's undefined.
If I dump response.rows[i].elements to console I see the value set to "ZERO_RESULTS".
function calcDistance() {
var finalDistance = "";
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [autocomplete.getPlace().geometry.location],
destinations: [autocomplete2.getPlace().geometry.location],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
console.log(response.rows[i].elements);
console.log(response.rows[i].elements.status);
for (var j = 0; j < results.length; j++) {
var element = results[j];
//alert('status' + results.status);
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
}
Console Log
You have a typo in your code. elements is an array. response.rows[i].elements.status is undefined, response.rows[i].elements[0].status works.
code snippet:
function calcDistance() {
var finalDistance = "";
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: ["New York, NY"],
destinations: ["Newark, NJ"],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
console.log(response.rows[i].elements);
console.log(response.rows[i].elements[0].status);
for (var j = 0; j < results.length; j++) {
var element = results[j];
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
}
function initialize() {
calcDistance();
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Why doesn't the javascript code work when I open the website

I am a JavaScript beginner, but I'm trying to put a route on a google maps with the Google Maps Directions API and Google Maps Javascript API. If I start the website it doesn't show me any route, but if I execute the commands at the Google Chrome Console it shows me the route. picture from the Google Chrome Console
<html>
<body>
<div id="map" style="width:100%;height:500px;"></div>
<script>
function requestRoute(origin1, origin2, destination1, destination2, waypoints) {
var directionsService = new google.maps.DirectionsService();
var myoutput = [];
var request = {
origin: new google.maps.LatLng(origin1, origin2),
destination: new google.maps.LatLng(destination1, destination2),
waypoints: waypoints,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status)
{ if (status == google.maps.DirectionsStatus.OK)
{
for (var x = 0; x < result.routes[0].legs.length; x++){
var myRoute = result.routes[0].legs[x];
for (var i = 0; i < myRoute.steps.length; i++) {
for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
myoutput.push(myRoute.steps[i].lat_lngs[j]);
}
}
}
} else{
alert(status)
}
});
return myoutput;
};
function processWaypoints(waypoints) {
var myarray = waypoints;
var myoutput = []
for (var x = 0; x < waypoints.length; x++){
myoutput.push({location: new google.maps.LatLng(myarray[x][0], myarray[x][1]), stopover: false});
};
return myoutput;
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: {lat: 12, lng: 15},
scrollwheel: false
});
var waypoints1 = processWaypoints([[-34.6036844, -58.3815591]]);
var points1 = requestRoute(-33.4488897, -70.6692655, -24.7821269, -65.4231976, waypoints1);
var routLine1 = new google.maps.Polyline(
{
path: points1,
strokeColor: "#FFC107",
strokeOpacity:0.8,
strokeWeight:4
}
);
routLine1.setMap(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key='MyGoogleMapsAPIKey'&callback=initMap">
</script>
</body>
</html>
Has anybody an idea what is wrong in my code?
The problem you're having is that the directionsService call is asynchronous. at the time myoutput is returned from requestRoute it is still an empty array. I restructured:
<html>
<body>
<div id="map" style="width:100%;height:500px;"></div>
<script>
var map;
function requestRoute(origin1, origin2, destination1, destination2, waypoints) {
var directionsService = new google.maps.DirectionsService();
var myoutput = [];
var request = {
origin: new google.maps.LatLng(origin1, origin2),
destination: new google.maps.LatLng(destination1, destination2),
waypoints: waypoints,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status)
{ if (status == google.maps.DirectionsStatus.OK)
{
for (var x = 0; x < result.routes[0].legs.length; x++){
var myRoute = result.routes[0].legs[x];
for (var i = 0; i < myRoute.steps.length; i++) {
for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
myoutput.push(myRoute.steps[i].lat_lngs[j]);
}
}
}
plotRoute(myoutput);
} else{
alert(status)
}
});
// return myoutput;
};
function processWaypoints(waypoints) {
var myarray = waypoints;
var myoutput = []
for (var x = 0; x < waypoints.length; x++){
myoutput.push({location: new google.maps.LatLng(myarray[x][0], myarray[x][1]), stopover: false});
};
return myoutput;
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: {lat: 12, lng: 15},
scrollwheel: false
});
var waypoints1 = processWaypoints([[-34.6036844, -58.3815591]]);
requestRoute(-33.4488897, -70.6692655, -24.7821269, -65.4231976, waypoints1);
}
function plotRoute(points1){
var routLine1 = new google.maps.Polyline(
{
path: points1,
strokeColor: "#FFC107",
strokeOpacity:0.8,
strokeWeight:4
}
);
routLine1.setMap(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAJLxeMko3jmj7ImPv96sVt-eyP7FtixQc&callback=initMap">
</script>
it's not pretty, but you get the idea.

Google Maps Roads API returns duplicate coordinates and placeIds

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.

Google Maps clear placed MarkerClusters on new search

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();
}

Categories