I am having trouble clearing any existing polylines before displaying a new one. I've already tried more than 5 different methods (array length = 0, MVCArray clear, polylines.setMap(null), etc) that I found on the web. I am using google maps V3, and here's the code from my js file
// initialize the google map
var latlng = new google.maps.LatLng(37.775, -122.418333);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// declare bounds object
var bounds = new google.maps.LatLngBounds();
// run the following functions when Routes dropdown box is changed
$("#routeID").change(function(){
// when JSON object is retrieved, delete existing overlays
deleteOverlays();
if ($("#routeID").val() > 0) {
// get JSON object from routestations.php (route information, lat, lon for stations on the selected route)
$.getJSON('includes/routestations.php',{'routeID':$("#routeID").val()}, function(routeInfoJSON){
// plot the new overlays
overlays(routeInfoJSON);
});
}
});
// delete overlays (markers, polylines) to "reset" the map before displaying other overlays
deleteOverlays = function() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
// declare an empty array for markers
var markersArray = [];
//set infoWindow global
var infoWindow;
// Place layer objects (polylines, markers, etc) for the selected route
overlays = function(routeInfoJSON) {
// declare polylinesArray
var polylinesArray = [];
for(var i=0; i < routeInfoJSON.config.station.length; i++){
// create point, marker objects
var point = new google.maps.LatLng(parseFloat(routeInfoJSON.config.lat[i]),parseFloat(routeInfoJSON.config.lon[i]));
var marker = new google.maps.Marker({
position: point,
map: map,
title: routeInfoJSON.config.station[i]
});
// push marker into markersArray (for future removal purposes only)
markersArray.push(marker);
// push lat/lon into polylinesArray
polylinesArray.push(point);
// set the marker on the map
marker.setMap(map);
// set & display infoWindow content
(function(i, marker){
if(!infoWindow){
infoWindow = new google.maps.InfoWindow();
}
var html = '';
google.maps.event.addListener(marker, 'click', function() {
// get JSON object from routestations.php (route information, lat, lon for stations on the selected route)
$.getJSON('includes/schedule.php', function(schedJSON){
// look through the stations in the schedule to match it with the user-selected station
for (var n = 0; n < schedJSON.station.length; n++) {
// if we find the station in the JSON that matches the user-selected station, then execute -->
if (schedJSON.station[n].abbr == routeInfoJSON.config.station[i]){
var html = "<div id=infoWindow class=info>";
html = html + "<h3>Train Arrival Times for '" + schedJSON.station[n].name + "' Station</h3>";
// set html for inforWindow
for (var c = 0; c < schedJSON.station[n].eta.length; c++) {
html = html + "<strong>To " + schedJSON.station[n].eta[c].destination + ": ";
html = html + "</strong>" + schedJSON.station[n].eta[c].estimate + "<br /><br />";
}
html = html + "</div>";
}
}
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
});
})(i, marker);
// extend bound object with each LatLng
bounds.extend(point)
}
// Adjust the map to new bounding box
map.fitBounds(bounds);
// start polylines codes
var polyLine = new google.maps.Polyline({
path: polylinesArray,
strokeColor: routeInfoJSON.color,
strokeOpacity: 0.8,
strokeWeight: 5
});
// set polyline on map
polyLine.setPath(polylinesArray);
polyLine.setMap(map);
}
could you please help me figure it out?
Thank you!
hope this help
//global path
var path = null;
...
//create new polyline
var polyLine = new google.maps.Polyline({
path: polylinesArray,
strokeColor: routeInfoJSON.color,
strokeOpacity: 0.8,
strokeWeight: 5
});
//delete old
var prepath = path;
if(prepath){
prepath.setMap(null);
}
//new polyline
polyLine.setMap(this.map);
// assign toglobal var path
path = polyLine;
Related
I am working with Google maps API(latest). So far, i can able to create and removing(on add operation) route with the help of polylines and markers.
Problem is when i try to modify(on update mode) the maps populates(dynamically) the route which i saved but if try to remove/modify existing route the marker removes but polyline dont.
tried poly.setMap(null);. but doesn't work.
on page load :
after removing any marker : (the last one got removed)
And you can see marker has been removed but polyline is still there
CODE(not working on fiddle):
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// if update/edit model populate map dynamically
populateLatLng();
// Add a listener for the click event
map.addListener('click', addLatLng);
map.addListener('click', function() {
getPathVariableCode(poly);
});
}
function populateLatLng() {
var path = '[{"lat":24.96078338154793,"lng":67.10892827306634},{"lat":24.934323836524374,"lng":67.07047612462884},{"lat":24.926851877301345,"lng":67.08111912999993},{"lat":24.90816999805268,"lng":67.06669957433587},{"lat":24.917822655664953,"lng":67.0519366959179},{"lat":24.911102310371437,"lng":67.03740863310293}]' //dynamic array
path = JSON.parse(path);
for (k = 0; k < path.length; k++) {
var marker = new google.maps.Marker({
position: path[k],
title: '#' + k,
map: map
});
markers.push(marker);
poly = new google.maps.Polyline({
path: path,
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function getPathVariableCode(line) {
var getLocation = '';
var locationArr = [];
var pathArr = line.getPath();
for (var i = 0; i < pathArr.length; i++) {
var codeStr = [];
codeStr = {
'lat': pathArr.getAt(i).lat(),
'lng': pathArr.getAt(i).lng()
};
locationArr.push(codeStr);
document.getElementById('locationCordinates').value = JSON.stringify(locationArr);
}
};
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
getPathVariableCode(poly);
}
}
}
#map {
height: 200px;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
Your code is quite problematic but I was able to successfully get a simplified working version of what you're trying to achieve here (if I understood correctly).
Try the code below. Just click on the map to add markers and then click on those markers to remove both the markers and their corresponding lines.
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event, path = false) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map,
id: new Date()
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id === marker.id) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
}
}
}
I hope this helps point you in the right direction.
I'm doing an application with google maps API that have a JSON with the marker's coordinates. Then I draw polylines between the markers. I also implemented a function with a onclick event that creates a new marker inside the polyline. This marker has to show information of the previous marker in the polyline (the one taked of the JSON, not a clicked one). But I don't know how to take the previous vertex(marker) of a selected polyline.
Code:
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
noClear: true,
panControl: true,
scaleControl: false,
streetViewControl:false,
overviewMapControl:false,
rotateControl:false,
mapTypeControl: true,
zoomControl: false,
};
var map = new google.maps.Map(document.getElementById('map'), options);
// JSON
$.getJSON("loc.js", function(json) {
console.log(json);
});
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://labs.google.com/ridefinder/images/mm_20_red.png" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map:map
});
infoPoly(map, flightPath, data);
//Calculate polylines distance
google.maps.LatLng.prototype.kmTo = function(a){
var e = Math, ra = e.PI/180;
var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
var g = this.lng() * ra - a.lng() * ra;
var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
(c) * e.pow(e.sin(g/2), 2)));
return f * 6378.137;
}
google.maps.Polyline.prototype.inKm = function(n){
var a = this.getPath(n), len = a.getLength(), dist = 0;
for (var i=0; i < len-1; i++) {
dist += a.getAt(i).kmTo(a.getAt(i+1));
}
return dist;
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data){
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
If I click in the blue arrow, I create a marker on that point of the polyline. I that marker it takes the values of the previous one.
You can use the geometry library .poly namespace isLocationOnEdge method to determine which segment of the polyline the clicked point (new marker) is on.
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
var betweenStr = "result no found";
for (var i=0; i<flightPath.getPath().getLength()-1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i+1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between "+i+ " and "+(i+1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr+"<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk,'click');
});
proof of concept fiddle
code snippet:
var infowindow = new google.maps.InfoWindow();
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
};
var map = new google.maps.Map(document.getElementById('map'), options);
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = "http://labs.google.com/ridefinder/images/mm_20_red.png";
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
infoPoly(map, flightPath, data);
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
for (var i = 0; i < flightPath.getPath().getLength() - 1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i + 1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between " + i + " and " + (i + 1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk, 'click');
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
var json = [{
lat: 38.931808,
lng: -74.906606,
tm: 0
}, {
lat: 38.932442,
lng: -74.905147,
tm: 1
}, {
lat: 38.93311,
lng: -74.903473,
tm: 2
}, {
lat: 38.933777,
lng: -74.901671,
tm: 3
}, {
lat: 38.930739,
lng: -74.912528,
tm: 1000
}];
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>
INITIALIZING
When you are creating those markers in the for loop, add them to a map [Data structure] that you define (empty) before the loop. In the map markers will be stored. Their keys - concatenated lat/lng.
var initial_markers = {}; //before for loop
initial_markers[data.lat+"-"+data.lng] = marker; //after each marker initialization
Count them, so you know how many there are initial_marker_count, because you cannot get length of size of a map[data structure]
DETECTION
When you have clicked on a polyline, I don't think you can get exactly the part of polyline that is clicked, so you need to get it yourself. The steps are:
Get the coordinate of click event
Loop through the markers
Take their coordinates
Check if the clicked point on the map is on the line between those two points
If is, take the first of those two points
DETECTION PSEUDOCODE
var prev_marker;
for (var i=initial_markers; i<initial_marker_count-2; i++) {
if( isPointOnLine(initial_markers[i], initial_markers[i+1], clicked_point) {
prev_marker = initial_markers[i];
break;
}
}
The only reason I am saying that this is pseudocode, is because I don't know hor to find if point is on the line between two points in Google maps. And you should write that isPointOnLine() functions. Apart from that - the idea is given. Hope You appreciate it.
All of my markers are coming from an AJAX call and are accurately placed on the map. However, the initial view is fully zoomed out, along the equator, in North America.
I know the solution lays somewhere with bounds.extend and map.fitBounds but apparently I'm doing it wrong.
I've always had an issue with this, so hopefully someone can help elevate this thorn in my side:
var map;
var markers = [];
var home_marker;
function initialize() {
// Display a map on the page
if ( document.contains(document.getElementById("map_canvas")) ) {
bounds = new google.maps.LatLngBounds();
map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 12,
center: new google.maps.LatLng(48.4222, -123.3657)
});
// a new Info Window is created
infoWindow = new google.maps.InfoWindow();
// Event that closes the InfoWindow with a click on the map
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
// Add Home Marker
home_marker = new google.maps.Marker({
position: new google.maps.LatLng(user_address_lat, user_address_lng),
map: map,
icon: '/images/map-icon-your-home.png'
});
}
}
function displayMarkers( properties ) {
// this variable sets the map bounds and zoom level according to markers position
var bounds = new google.maps.LatLngBounds();
// For loop that runs through the info on markersData making it possible to createMarker function to create the markers
for (var i = 0; i < properties.length; i++){
var latlng = new google.maps.LatLng(properties[i]['latitude'], properties[i]['longitude']);
var price_current = properties[i]['price_current'];
var bedrooms = properties[i]['bedrooms'];
var total_baths = properties[i]['total_baths'];
var listing_id = properties[i]['listing_id'];
createMarker( latlng, price_current, bedrooms, total_baths, matrix_unique_ID );
// Marker’s Lat. and Lng. values are added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with API’s fitBounds() function
map.fitBounds(bounds);
}
function createMarker( latlng, price, bedrooms, bathrooms, matrix_id ) {
var formatted_price = accounting.formatMoney(price, '$', 0);
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: '/images/map-icon.png'
});
google.maps.event.addListener(marker, 'click', function() {
// Variable to define the HTML content to be inserted in the infowindow
var iwContent = '<div class="row"><div class="small-12 columns"><img src="http://www.mywebsite.com/properties/'+listing_id+'/image-'+matrix_id+'-1.jpg"></div></div>' +
'<div class="row"><div class="small-12 columns"><p class="price-current text-center">'+formatted_price+'</p></div></div><hr>' +
'<div class="row"><div class="small-6 columns"><p class="bedrooms"><span class="fw-semi-bold">Beds:</span> '+bedrooms+'</p></div>' +
'<div class="small-6 columns"><p class="total-baths"><span class="fw-semi-bold">Baths:</span> '+bathrooms+'</p></div></div>';
// including content to the infowindow
infoWindow.setContent(iwContent);
// opening the infowindow in the current map and at the current marker location
infoWindow.open(map, marker);
});
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
Make a new Part to your script or make a new one, and code it specificly to change zoom in camera ammount and, add ui button for it.
My goal is to allow the user to filter results based on the option they select at the top of the map. If anyone could help me clean up this code and make it functional I would greatly appreciate your efforts
This first part sets up the 4 options I would like to filter by.
<div id="Filters" style="margin:5px;background:#f4f4f4;border:1px solid #888;padding:5px 5px 5px 10px;">
<label style="color:#555;font-size:12px; font-weight:bold;" for="tags">Filter by: </label>
<select id="tags" style="outline:none;">
<option value="all">All</option>
<option value="Western">Western</option>
<option value="Central">Central</option>
<option value="Eastern">Eastern</option>
</select>
</div>
(function() {
// Creating an array that will contain hhs icons
var hhsIcons = [];
hhsIcons['Eastern'] = new google.maps.MarkerImage('{!$Resource.markerE}' );
hhsIcons['Western'] = new google.maps.MarkerImage('{!$Resource.markerW}' );
hhsIcons['Central'] = new google.maps.MarkerImage('{!$Resource.markerC}' );
window.onload = function() {
// Create object literal containing the properties of the map
var options = {
zoom:5,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
// Create the map
var map = new google.maps.Map(document.getElementById('map'),
options);
var homeControlDiv = document.createElement('DIV');
var homeControl = new HomeControl(homeControlDiv, map);
homeControlDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(homeControlDiv);
var eastControlDiv = document.createElement('DIV');
var eastControl = new EastOnly(eastControlDiv, map);
eastControlDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(eastControlDiv);
var jsonData = {'jsonaccounts':
[
<apex:repeat value="{!Accounts}" var="abc">
{
'lat': '{!abc.Latitude__c}',
'lng': '{!abc.Longitude__c}',
'hhs': '{!abc.HHS_Region__c}'
},
</apex:repeat>
]};
var accountname = [];
var director = [];
var vp = [];
var division = [];
//Add field data for each account into respective arrays
<apex:repeat value="{!Accounts}" var="acc">
accountname.push("{!acc.name}");
director.push("{!acc.hhs_director__r.name}");
vp.push("{!acc.area_vp__r.name}");
division.push("{!acc.HHS_Region__c}");
</apex:repeat>
// Create a variable that will hold the InfoWindow object
var infowindow;
var markers = [];
// Loop through the jsondata
for (var i = 0; i < jsonData.jsonaccounts.length; i++) {
var jsonaccounts = jsonData.jsonaccounts[i];
// Create marker data
var myMarkerData = { // collecting all custom data that you want to add
region : jsonaccounts.hhs, // to the marker object within an array.
}
When I add the markers, I think I need to make categories for each so it will let me filter by the specific category
// Adding the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(jsonaccounts.lat,
jsonaccounts.lng),
map: map,
icon: hhsIcons[jsonaccounts.hhs],
data: myMarkerData
});
marker.region = jsonaccounts.hhs;
markers.push(marker);
alert(markers[i].region);
// Wrap the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Create the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker,
'click', function() {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Set the content of the InfoWindow
infowindow.setContent('<b>' + accountname[i] + '</b>' +
'<br/>Director: ' + director[i] +
'<br/>VP: ' + vp[i] +
'<br/>Division: ' + division[i] +
// Tie the InfoWindow to the marker
infowindow.open(map, marker);
});
})(i, marker);
}
}; })();
I am not sure if this code is useful, but it was where I left off
marker.region = region;
markers.push(marker); function
hide(region) {
for (var i=0; i<map.markers.length; i++) {
if (map. markers[i].region == region) {
map.markers[i].setVisible(false);
}
}
</script>
In your last code block you use map.markers while it should be just markers.
I have a forloop that has a call to a function inside of it. Within that function, I'm pushing values to an array called markers.
Is there a way to access the values of the markers array outside of the forloop?
Here's the code:
<script type="text/javascript">
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var map = null;
geocoder = new google.maps.Geocoder();
var side_bar_html = "";
var icon = '';
var markers = [];
function codeAddress(this_address,index,callback) {
geocoder.geocode( { 'address': this_address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call(window,index,results[0].geometry.location)
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize() {
// create the map
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(46.90, -121.00),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (var i = 0; i < businesses.length; i++) {
codeAddress(businesses[i].address,i,function(i,point){
var description = businesses[i].description;
if(businesses[i].business_type == "Wine"){
//http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|00CC99|000000
icon = 'http://google-maps-icons.googlecode.com/files/wineyard.png';
}else if(businesses[i].business_type == "Golf"){
icon = 'http://google-maps-icons.googlecode.com/files/golf.png';
}else{
icon = 'http://google-maps-icons.googlecode.com/files/festival.png';
}
var marker = createMarker(point,businesses[i].name,description,icon);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});//End codeAddress-function
}//End for-loop
console.log(markers);
var markerCluster = new MarkerClusterer(map, markers);
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html,icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
markers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (markers.length-1) + ')">' + name + '<\/a><br />'+html+'<br />';
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(markers[i], "click");
}
</script>
As you can see, the last line says "var markerCluster = new MarkerClusterer(map, markers);" This is where I want to be able to access the information from.
Thanks!
The problem is you're not accounting for the asynchronous nature of the call to codeAddress. You're calling that function in a loop, which is triggering a series of calls to the Google Maps API.
You are running this line:
var markerCluster = new MarkerClusterer(map, markers);
...even before the callbacks have been triggered.
To fix, maintain a counter. Each time the callback is triggered increase that counter by 1. Once it is equal to businesses.length you know all the addresses have been geo-coded, and all markers have been added to the array. Now you can create the MarkerCluster.
Yes, Declare it before the for loop.
var markers
for(....
Bring the definition of the marker outside of the for loop ...
var markers = new Array ();
for (var i = 0; i < businesses.length; i++) {
markers[i] = ...