Call markers based on radio button value - json

I am trying to call markers to a google map based on a value (year as a string). I thought by putting an on click event to listen for when the radio class is clicked, that I could initialize the $.getJSON and set the value for the year.
How can initialize the $.getJSON call when the radio button is clicked and base the variable yearValue on which radio button is checked?
Also, if I wanted to reset the markers each time a new radio button is clicked, would I need to put all of the markers in an array, set them to the map, then clear the array when a new radio button value is checked (say I choose 2014 instead of 2015?). How can I clear the markers when a new radio button is checked so that I don't see both years at the same time?
var map;
var mapProp;
var url = 'https://data.montgomerycountymd.gov/resource/5pue-gfbe.json?$limit=50000';
var count;
var marker;
var manyCategory = [];
var category = [];
var yearValue;
function initMap() {
mapProp = {
center: new google.maps.LatLng(39.154743, -77.240515),
zoom: 10
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
}
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
}
$(document).ready(function() {
if ($('input:radio[name="year"]').is("checked")) {
yearValue = $(this).val();
}
initMap();
$('.radioClass').on('click', function() {
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < data.length; i++) {
var newDate = data[i].inspectiondate;
if (data[i].violation22 === "Out of Compliance" && newDate.slice(0, 4) === yearValue) {
if (data[i].hasOwnProperty('latitude')) {
count++;
var message = "<div>" + data[i].organization + "<br>" + (data[i].inspectiondate).slice(0, 10) + "</div>";
var uniqueIcon;
if (data[i].category === "Private School" || data[i].category === "Public School- Elementary" || data[i].category === "Public School- High" || data[i].category === "Public School- Middle") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/blue.png";
} else if (data[i].category === "Market" || data[i].category === "Carry Out" || data[i].category === "Snack Bar" || data[i].category === "Caterer" || data[i].category === "Restaurant") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/purple.png"
} else if (data[i].category === "Nursing Home" || data[i].category === "Hospital" || data[i].category === "Assisted Living") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/red.png"
} else {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png";
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude),
title: "Hello, world. I received a food violation in 2015",
animation: google.maps.Animation.DROP,
icon: uniqueIcon,
});
marker.setMap(map);
//console.log(data[i].inspectionresults);
addInfoWindow(marker, message);
manyCategory.push(data[i].category);
}
}
}
//;
$.each(manyCategory, function(i, el) {
if ($.inArray(el, category) === -1) category.push(el);
})
//console.log(count);
//console.log(manyCategory);
//console.log(category);
});
});
});
h1,
#icons,
#radioDiv {
text-align: center;
}
#map {
margin: 0 auto;
width: 700px;
height: 400px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<h1>Rodent Violations</h1>
<div id="radioDiv">
<input type="radio" name="year" value="2015" class="radioClass">2015
<input type="radio" name="year" value="2014" class="radioClass">2014
</div>
<div id="icons">
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/blue.png">School
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/purple.png">Restaurant
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/red.png">Healthcare
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png">All other
</div>
<div id="map"></div>

You need an array fo markers globally visibile that hold all the markers you create for let you clean them before you show the new markers.
var myMarkers
add the begin of the callback function clear the markers setting maps to null
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < myMarkers.length; i++) {
myMarkers[i].setMap(null);
}
myMarkers = []; // empty the array
.......
popluate the myMArkers Array with all the marker you create
marker.setMap(map);
addInfoWindow(marker, message);
myMarkers.push(marker);

Related

Google maps not working IE11 (sharepoint 2010)

I have a code to show Google Maps in my list on Sharepoint 2010. Code plot list items in the map. Work great with Edge and Chrome, but on IE not.
In IE console error on this line (object doesn't support this action (error 445))
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
Full code on Sharepoint:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" type="text/javascript"></script><script src="http://maps.google.com/maps/api/js?key=MY KEY" type="text/javascript"></script><script type="text/javascript">
/* *****************************************************
AND NOW SOME VARIABLES YOU MAY WANT TO CHANGE.
***************************************************** */
var mapWidth = "1725px"; //the width of the map
var mapHeight = "400px"; //the height of the map
//if true the coordinates (latitude, longitude) will be used
//if false the addresses (street, zip, city, country) will be used
var useCoordinates = true;
//if true the map will not be shown by default
//if false the map will be shown by default
var hideMapUntilClick = false;
//if 0 absolutely no warning- and error-alerts will be written to a log-div
//if 1 the warning- and error-alerts will be written to a log-div
//if 2 the warning- and error-alerts will be alerted via javascript-alert
var showWarningAndErrorAlerts = 1;
//the internal-names of list-columns (not the display-name!)
var colLinkTitleInternalName = "ows_Nome_x0020_Instala_x00e7__x00e3_"; //will be used as the title of the geo-markers
var colLongitudeInternalName = "ows_Longitude"; //useCoordinates == true
var colLatitudeInternalName = "ows_Latitude"; //useCoordinates == true
var colStreetInternalName = "WorkAddress"; //useCoordinates == false
var colStreetDisplayName = "EndereƧo"; //useCoordinates == false
var colZipInternalName = "WorkZip"; //useCoordinates == false
var colCityInternalName = "WorkCity"; //useCoordinates == false
var colCountryInternalName = "WorkCountry"; //useCoordinates == false
var defaultCountryValue = "Brazil"; //the default country which will be used if no country-name will be found in the list-column
//default position (Germany: 51.165691,10.451526) > used if no markers will be set to the map
var defaultLatitude = -15.77972;
var defaultLongitude = -47.92972;
//some language-specific messages
var resxGoogleMapsLink = "Google-Map"; //the name of new menu-point in the menu-toolbar of the sharepoint-list
var resxGoogleMapsLinkTitle = "Menu: Show or hide Google-Map"; //the title which will be visible while hovering
var resxAlertsMessageText = resxGoogleMapsLink+": There are # hints!"; //the hint which will be visible if configuration warnings or errors occured.
var resxAlertsMessageTextTitle = "Click here to show or hide the hints!"; //the title which will be visible while hovering
/* *******************************************************************
NOW DO NOT CHANGE ANYTHING IF YOU ARE NOT FAMILIAR WITH JAVASCRIPT!
******************************************************************* */
var isSharePoint2010 = true;
var hasMapBeenLoadedInitially = false;
var idOfMapDiv = "divGoogleMapForSharePointList";
var idOfCustomLogDiv = "divCustomLog";
var idOfCustomLogOverview = "divCustomLogOverview";
var noOfCustomLogEntries = 0;
var noOfMaxGeocodingRequest = 10;
//the attribute-name of the column "id" > will be used for a) finding the id of a certain row and b) for building the ajax-request-url
var colID = "ID";
//now some templates for jquery-selects
var jQuerySelect_2007_GetListRowByAttributeCTXName = "table[CTXName]";
var jQuerySelect_2010_GetListRowByAttributeCTXName = "div[CTXName]";
function InitializeGoogleMapForSharePointList()
{
BuildGoogleMapCustomLogForSharePointList();
if(!DoPreCheckForInitializationOfGooglemapsForSharePointList())
{
//pre-check not successfully done > abort now!
customAlert("The Pre-Check has not been successfully! > Abort now.");
return;
}
DoSchemaCheckAndBuildGoogleMapIconForSharePointList();
}
function DoSchemaCheckAndBuildGoogleMapIconForSharePointList()
{
//get the schema-data for the list
$.get(BuildAjaxRequestUrlForSharePointListSchemaOnly(), {}, function (xml)
{
//find all necessary internal-field-names
var arrNeccessaryFields = new Array();
arrNeccessaryFields.push(colLinkTitleInternalName);
if(useCoordinates)
{
arrNeccessaryFields.push(colLatitudeInternalName);
arrNeccessaryFields.push(colLongitudeInternalName);
}
else
{
arrNeccessaryFields.push(colStreetInternalName);
arrNeccessaryFields.push(colZipInternalName);
arrNeccessaryFields.push(colCityInternalName);
arrNeccessaryFields.push(colCountryInternalName);
}
//check all neccessary internal-field-names
var foundAllNeccessaryFields = true;
for(i=0;i<arrNeccessaryFields.length;i++)
{
//getting <xml><s:Schema><s:ElementType><s:AttributeType name="[internal-field-name]">
var xmlQuery = 'xml > *:first > *:first > *[name='+arrNeccessaryFields[i]+']';
if($(xmlQuery, xml).length<1)
{
foundAllNeccessaryFields = false;
customAlert("Schema-Check failed for internal-field-name '"+arrNeccessaryFields[i]+"'. The field is not available in this list.");
}
}
//check if the neccessary fields have been found
if(foundAllNeccessaryFields)
{
BuildGoogleMapIconForSharePointList();
}
else
{
var ajaxRequestLinkTag = 'ajax-request for list-schema';
customAlert("Hint: You can get the internal names of the columns by calling the "+ajaxRequestLinkTag+" for the current sharepoint-list manually.");
customAlert("Schema-Check failed. Abort now!");
}
});
}
function DoPreCheckForInitializationOfGooglemapsForSharePointList()
{
//check if this is SharePoint2010 or not
//if it is not 2010 it is assumed that it is 2007
if(typeof(_fV4UI)!='undefined')
{
//the checked javascript-variable exists only in 2010
isSharePoint2010 = true;
}
else
{
isSharePoint2010 = false;
}
//for the first shot: support only one table
//for further version we could support more tables (table[class=ms-listviewtable].length>1)
var noOfListViews = $("table[class=ms-listviewtable]").length;
if(noOfListViews==0)
{
//no list-view exists > there is no need to show google-maps
customAlert("There is no list-view available on this site. > No need to show google-maps. > Abort now.");
return false;
}
else if(noOfListViews>1)
{
//there are more than one list-view > this is not supported at the moment
customAlert("There are more than one list-views on the site. This is not supported at the moment. > Abort now!");
return false;
}
//check if multi-lookup exists
if($("table[FieldType=LookupMulti]").length>0)
{
//If there are columns in the list-view which are of type multi-lookup the ajax-call (via owssrv.dll) will return zero results.
var multiMsg = "Multi-lookup exists! Please remove the mulit-lookup-column or use another view (otherwise the ajax-request will receive an empty result). > Abort now!";
multiMsg += "\n\nColumns which are of type multi-lookup are (the display-name will be shown):";
$("table[FieldType=LookupMulti]").each(function(){
var displayName = $(this).attr("displayName");
multiMsg += "\n- "+displayName;
});
customAlert(multiMsg);
return false;
}
//check if javascript-variable exists > we need ctx to get the id of the sharepoint-list
if(ctx==null)
{
//this javascript-variable is essential for getting the list-id and the list-view-id.
customAlert("The javascript-variable 'ctx' does not exist within the html-dom. > Abort now!");
return false;
}
//all checks passed - return true
return true;
}
function BuildGoogleMapCustomLogForSharePointList()
{
if(showWarningAndErrorAlerts!=1)
{
return;
}
var divCustomLogOverview = '<div title="'+resxAlertsMessageTextTitle+'" onclick="ToggleCustomLog();" id="'+idOfCustomLogOverview+'" style="margin: 10px; cursor: pointer; color: red; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLogOverview);
var divCustomLog = '<div id="'+idOfCustomLogDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLog);
}
function ToggleCustomLog()
{
//show or hide
$("#"+idOfCustomLogDiv).toggle();
}
function ToggleGoogleMapDiv()
{
//check if the map will be called for the first time
if(!hasMapBeenLoadedInitially)
{
ShowGoogleMapForSharePointList();
}
//show or hide
$("#"+idOfMapDiv).toggle();
}
function BuildGoogleMapIconForSharePointList()
{
//searching for the correct position in the menu-toolbar (ms-menutoolbar)
$("td.ms-toolbar").each(function(j){
if($(this).attr("width")=="99%")
{
//insert a new menu-item before the found placeholder
//var newMenuItem = '</internal-name-of-column><td class="ms-separator">';
var newMenuItem = '<td class="ms-separator">';
newMenuItem += '<img src="/_layouts/images/blank.gif" alt=""/>';
newMenuItem += '</td>';
newMenuItem += '<td nowrap="true" class="ms-toolbar">';
newMenuItem += '<span title="'+resxGoogleMapsLinkTitle+'">';
newMenuItem += '<div nowrap="nowrap" hoverinactive="ms-menubuttoninactivehover" hoveractive="ms-menubuttonactivehover" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" class="ms-menubuttoninactivehover">';
newMenuItem += '<a onclick="javascript:ToggleGoogleMapDiv();return false;" href="#" style="cursor: pointer; white-space: nowrap;">'+resxGoogleMapsLink+'</a>';
newMenuItem += '</div>';
newMenuItem += '</span>';
newMenuItem += '</td>';
$(this).before(newMenuItem);
}
});
//adding map-canvas as div-tag to the dom
var divMapCanvas = '<div id="'+idOfMapDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().before(divMapCanvas);
//check if the map should be shown as soon as possible or if it should be hidden until the user clicked the new menu-point
if(!hideMapUntilClick)
{
ToggleGoogleMapDiv();
}
}
//gets the complete list-schema and one row with all its values (not filtered by the current used view)
function BuildAjaxRequestUrlForSharePointListByID_Template()
{
if(ctx!=null)
{
//build the url of the ajax-request
return ctx.HttpRoot+'/_vti_bin/owssvr.dll?XMLDATA=1&List=' + ctx.listName + '&Query=*&FilterField1='+colID+'&FilterValue1=';
}
}
//gets the list-schema and no rows
function BuildAjaxRequestUrlForSharePointListSchemaOnly()
{
//build the url of the ajax-request
return BuildAjaxRequestUrlForSharePointListByID_Template()+'-1';
}
function ShowGoogleMapForSharePointList()
{
//build the url of the ajax-request
var urlTemplate = BuildAjaxRequestUrlForSharePointListByID_Template();
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
//check if the number of geocodings will exceed the max-number
if(!useCoordinates && $(jQuerySelect_GetListRowByAttributeCTXName).length > noOfMaxGeocodingRequest)
{
var linkToStatusCodes = '<a title="Statuscodes of geocoding-responses from Google-Maps" target="_blank" href="http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/services.html#GeocodingStatusCodes">OVER_QUERY_LIMIT-Status</a>';
var tooManyMsg = "Hint: In the current view of the SharePoint-List there are more than "+noOfMaxGeocodingRequest+" list-entries. ";
tooManyMsg += "This will result in an "+linkToStatusCodes+" by Google-Maps (and not all markers will be shown on the map). > You have 2 options: ";
tooManyMsg += "a) Change your view to get no more than "+noOfMaxGeocodingRequest+" list-entries or ";
tooManyMsg += "b) use the coordinates (longitude, latitude) of the addresses (they will be shown on the map).";
customAlert(tooManyMsg);
}
//get each row from list-view which is shown at the moment
$(jQuerySelect_GetListRowByAttributeCTXName).each(function(j)
{
var lat, lng, gmLatLng, gmMarker, title, customUrl, street, city, country;
var idOfListItem = $(this).attr(colID);
if(isSharePoint2010)
{
var linkToListItem = '<table height="auto" width="calcWidthpx"><tr class="ms-alternating ms-itmhover"><td height="100%" class="ms-vb-title" onmouseover="OnChildItem(this)">';
linkToListItem += $(this).parent().html();
linkToListItem += '</td></tr></table><span style="font-size:72pt;"></br></span>';
}
else
{
linkToListItem = $(this).parent().html();
linkToListItem = linkToListItem.replace(/100%/g, "auto"); //exchange tag-attributes for width and height
}
//build url for the ajax-request which reads all data for a certain row (for the current list-view)
customUrl = urlTemplate+idOfListItem;
//get the data for the row
$.get(customUrl, {}, function (xml)
{
$('xml > *:last > *', xml).each(function (i)
{
//get some data from the xml-response
title = $(this).attr(colLinkTitleInternalName);
if(isSharePoint2010)
{
var titleLength= title.length+185;
linkToListItem = linkToListItem.replace('calcWidth', titleLength);
}
if(useCoordinates)
{
//getting coordinates
lat = $(this).attr(colLatitudeInternalName);
lng = $(this).attr(colLongitudeInternalName);
if(typeof(lat)!='undefined' && typeof(lng)!='undefined')
{
gmLatLng = new google.maps.LatLng(lat, lng);
msgForInfoWindow = linkToListItem; //you may add more information-text here
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
else
{
customAlert(title +" has undefined lat+lng. > Do not add marker on map.");
}
}
else
{
//getting address
street = $(this).attr(colStreetInternalName);
zip = $(this).attr(colZipInternalName);
city = $(this).attr(colCityInternalName);
country = $(this).attr(colCountryInternalName);
//checking received values
if(typeof(street)=='undefined') street = ""; //optional
if(typeof(zip)=='undefined') zip = ""; //optional
if(typeof(city)=='undefined')
{
customAlert("The ajax-response got no city for '"+title+"'. > Do not add marker on map.");
return;
}
if(typeof(country)=='undefined') country = defaultCountryValue;
address = street+","+zip+","+city+","+country;
//getting coordinates
gmGeocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
if(results.length==0)
{
customAlert("Geocoding: There are no results for address '"+results[0].formatted_address+"'! Expected exactly one result. > Do not show any marker on map for this address.");
}
else if(results.length>1)
{
var msg = "Geocoding: There are too many ("+results.length+") results for given address! Expected exactly one result. > Do not show any marker on map for this address.\n\nFound addresses:\n";
for(i=0;i<results.length;i++)
{
var c = i+1;
msg += "\n"+c+": "+results[i].formatted_address;
}
customAlert(msg);
}
else
{
gmLatLng = results[0].geometry.location;
var msgForInfoWindow = linkToListItem+"<br>";
msgForInfoWindow += "<span style='font-size:0.8em;'>Koordinaten (Lat, Lon): "+gmLatLng+"<br>Adresse: "+results[0].formatted_address+"</span>";
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
}
else
{
customAlert("Geocode for address '"+address+"' was not successful for the following reason: " + status);
}
});
}
});
});
});
hasMapBeenLoadedInitially = true;
}
function SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, contentForInfoWindow)
{
var gmMarker = new google.maps.Marker({
position: gmLatLng,
map: gmMap,
title: title,
zIndex: 0
});
gmBounds.extend(gmLatLng);
gmMap.setCenter(gmBounds.getCenter());
gmMap.fitBounds(gmBounds);
if(contentForInfoWindow!=null && contentForInfoWindow!="")
{
var gmInfowindow = new google.maps.InfoWindow({
content: contentForInfoWindow
});
google.maps.event.addListener(gmMarker, 'click', function() {
gmInfowindow.open(gmMap,gmMarker);
});
}
}
function customAlert(msg)
{
if(msg==null || msg=="")
{
return;
}
else
{
var now = new Date();
msg = now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+": "+msg;
}
if(showWarningAndErrorAlerts==0)
{
//do nothing
}
else if(showWarningAndErrorAlerts==1)
{
//do log in log-div
msg = msg.replace(/\n/g, "<br/>");
msg += "<br/><br/>";
$("#"+idOfCustomLogDiv).append(msg);
noOfCustomLogEntries++;
$("#"+idOfCustomLogOverview).show();
var overviewText = resxAlertsMessageText.replace(/#/g, noOfCustomLogEntries);
$("#"+idOfCustomLogOverview).text(overviewText);
}
else if(showWarningAndErrorAlerts==2)
{
//do alert via javascript-alert
alert(msg);
}
else
{
//unsupported
}
}
//call initialization after the dom has been loaded completely > so it does not matter where this piece of javascript will be inserted in the dom
$(document).ready(InitializeGoogleMapForSharePointList);</script>
Result in Chrome e Edge:
Screenshot
Just to put an answer to this question, adding the meta tag of <meta http-equiv="X-UA-Compatible" content="IE=8"> would solve the issue.

Google Api Nearby Places on change of type, layer removed, but advertising stays, how can I remove the complete layer without reloading the page

I have custom code to create a nearby search of places on google map.
Each search type creates a new layer, removed when selecting a different search type, my problem is, even thought he layer is removed, here in Thailand we have "Google partners advertising" show dependant on the search type and this "Layer" doesnt get removed, but added to when creating a new search layer.
This is the code I use to create the search (in part):
Creating a layer (Google):
<div id="map_layers_google">
<input type="checkbox" name="map_google" id="map_google_restaurant" class="box" onclick="Propertywise.Maps.getDataWithinBounds('google_restaurant');" value="google_restaurant">
</div>
getDataWithinBounds: function(layer_name, except_this_area) {
if (!Propertywise.Design.is_ie8_or_less) {
this.layers_on_map[layer_name] = true;
this.getEntitiesWithinBounds(layer_name);
}
getEntitiesWithinBounds: function(entity_name) {
var $this = this;
if (!this.getBounds()) {
setTimeout(function() {
$this.getEntitiesWithinBounds(entity_name);
}, 20);
} else {
var layer_name, category;
var $this_input_el = jQuery("#map_" + entity_name);
jQuery("#map_updating").fadeIn('fast');
if (entity_name.indexOf('google') != -1) {
layer_name = "google";
category = entity_name.replace("google_", "");
} else if (entity_name.indexOf('school') != -1) {
layer_name = "schools";
category = entity_name.replace("schools_", "");
} else if (entity_name.indexOf('events') != -1) {
layer_name = "events";
category = entity_name.replace("events_", "");
} else {
layer_name = "transport";
this.toggleTransitLayer();
}
jQuery("#map_layers_" + layer_name + " input").each(function(index, value) {
var el_id = jQuery(this).attr("id");
var el_entity_name = el_id.replace("map_", "");
Propertywise.Maps.layers_on_map[el_entity_name] = false;
if (jQuery(this).is(":checked") && el_entity_name != entity_name) {
jQuery(this).attr("checked", false);
}
if (jQuery(this).is(":checked") && el_entity_name == entity_name) {
Propertywise.Maps.layers_on_map[entity_name] = true;
}
});
if (jQuery("#map_" + entity_name).is(':checked') || Propertywise.this_page == "school") {
if (layer_name == "google") {
infoWindow = new google.maps.InfoWindow();
Propertywise.Maps.removeMarkers(layer_name);
var request = {
bounds: Propertywise.Maps.map.getBounds(),
types: [category]
};
service = new google.maps.places.PlacesService(Propertywise.Maps.map);
service.radarSearch(request, function(results, status) {
jQuery("#map_updating").fadeOut('fast');
if (status != google.maps.places.PlacesServiceStatus.OK) {
return;
}
for (var i = 0, result; result = results[i]; i++) {
Propertywise.Maps.createMarker(result.geometry.location.lat(), result.geometry.location.lng(), {
place: result,
type: category
});
}
});
}
} else {
this.removeMarkers(layer_name);
jQuery("#map_updating").fadeOut('fast');
}
}
}
And this is the setup and remove each layer:
setUpLayers: function() {
var $this = this;
jQuery.each(this.layers, function(layer_name, value) {
Propertywise.Ajax.requests[layer_name] = [];
$this.layers[layer_name] = [];
});
},
removeMarkers: function(layer_name) {
if (Propertywise.Maps.map) {
var layer = this.layers[layer_name];
for (var i = 0; i < layer.length; i++) {
layer[i].setMap(null);
}
layer = [];
}
}
Here is link to screen shot of the problem.
screenshot
Question is, can anyone help with either changing the above to remove the complete layer(not just marker layer) or advise how to remove the advertising.. I understand this is part of terms of Google to display, but its unprofessional and looks terrible.
Best
Malisa

fill google maps autocomplete with prediction results

What I have at the moment is a place autocomplete which displays results for one country.
What I want to do is make it display results for more countries (limited to 2 or 3).
As I understand it, this is not possible with the current version of the autocomplete ( https://code.google.com/p/gmaps-api-issues/issues/detail?id=4233)
So what I'm going to do is get two lists of predictions and display those instead of the autocomplete result.
Is there any way to trigger the dropdown part of the autocomplete and populate it with the predictionslist?
triggered code in the onChange of the input:
var inputData = this.value;
var options = {
componentRestrictions: { country: "be" }
};
service = new google.maps.places.AutocompleteService();
var request = {
input: inputData,
componentRestrictions: {country: 'be'},
};
var secondaryRequest = {
input: inputData,
componentRestrictions: {country: 'lu'},
};
service.getPlacePredictions(request, callback);
service.getPlacePredictions(secondaryRequest, callback);
callback function:
function callback(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
//here I need to display that dropdown if it isn't already
// and then add the results of the current predictions.
}
UPDATE
Multiple countries filter in place autocomplete was introduced in version 3.27 of Maps JavaScript API in January 2017:
You can now restrict Autocomplete predictions to only surface from multiple countries. You can do this by specifying up to 5 countries in the componentRestrictions field of the AutocompleteOptions.
source: https://developers.google.com/maps/documentation/javascript/releases#327
Here's my demo solution. As mentioned in the comment. it uses several calls to get predictions and build up the result list with them. When a result is selected the address is geocoded.
This means 3 calls instead of 1 with the autocomplete, but so far I haven't found a way around it.
<!DOCTYPE html>
<html>
<head>
<title>Retrieving Autocomplete Predictions</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&v=3.exp"></script>
<script>
function initialize() {
$("#place").live("keyup", function (evt) {
// Clear any previously set timer before setting a new one
window.clearTimeout($(this).data("timeout"));
$(this).data("timeout", setTimeout(function () {
//whe the timeout has expired get the predictions
var inputData = $("#place").val();
service = new google.maps.places.AutocompleteService();
var request = {
input: inputData,
componentRestrictions: {country: 'be'},
};
var secondaryRequest = {
input: inputData,
componentRestrictions: {country: 'lu'},
};
$('#resultWindow').empty();
service.getPlacePredictions(request, callback);
service.getPlacePredictions(secondaryRequest, callback);
}, 1000));
});
function callback(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
return;
}
var resultHTML = '';
for (var i = 0, prediction; prediction = predictions[i]; i++) {
resultHTML += '<div>' + prediction.description + '</div>';
}
if($('#resultWindow').html() != undefined && $('#resultWindow').html() != ''){
resultHTML = $('#resultWindow').html()+ resultHTML;
}
if(resultHTML != undefined && resultHTML != ''){
$('#resultWindow').html(resultHTML).show();
}
//add the "powered by google" image at the bottom -> required!!
if($('#resultWindow').html() != undefined){
$('#resultWindow #googleImage').remove();
var imageHtml = $('#resultWindow').html() + '<img id="googleImage" src="powered-by-google-on-white2.png"/>';
$('#resultWindow').html(imageHtml);
}
}
function geocodeAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
}
else {
console.log("Error: " + google.maps.GeocoderStatus);
}
});
}
$('#resultWindow div').live('click',function(){
//get the coƶrdinates for the selected (clicked) address
$('#resultWindow').hide();
var address = $(this).text();
var addressParts = address.split(',');
$('#country').val(addressParts[2]);
$('#city').val(addressParts[1]);
$('#place').val(addressParts[0]);
if(address != ''){
geocodeAddress(address);
}
});
/*end custom autocomplete stuff*/
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style type="text/css">
#resultWindow{
position: fixed;
/* top: 0;
left: 0;
width: 100%;
height: 100%;*/
background-color: #fff;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
z-index: 10000;
border: 1px solid black;
color:black;
display:none;
}
</style>
</head>
<body>
<div id="placeholder">
<input type="text" id="place" style="width:200px;"/>
<label for="latitude">Latitude</label>
<input type="text" id="latitude"/>
<label for="longitude">Longitude</label>
<input type="text" id="longitude"/>
<label for="city">city</label>
<input type="text" id="city"/>
<label for="country">selected country</label>
<input type="text" id="country"/>
<div id="resultWindow"></div>
</div>
</body>
</html>

Weird Google Maps V2 Marker issue

Got this code, that only works when alert (markers.length); is uncommented.
When this javascript alert not shown I dont get any Markers.. Really weird!!
In the body tag I have <body onload="load()" onunload="GUnload()">
Previoslly the load() function is called and other functions :
function showAddress(address) {
if (geocoder) {//+', '+init_street
geocoder.getLatLng(address,
function(point) {
if (!point) {
document.getElementById("place").value="not found";
//alert(address + " not found");
} else {
// document.getElementById("place").value=point.y.toFixed(4) + "," + point.x.toFixed(4);
map.setCenter(point, 16);
marker.setPoint(point);
//marker.openInfoWindowHtml(address);
}
}
);
}
}
//from a point returns and address!
function showPointAddress(response) {
if (!response || response.Status.code != 200) {//not found
//alert("Status Code:" + response.Status.code);
document.getElementById("place").value="not found";
}
else {//found
map.setCenter(marker.getPoint(), 16);
place = response.Placemark[0];
document.getElementById("place").value=place.address;
//document.getElementById("place").value=marker.getPoint().toUrlValue();
}
}
// Creates a marker at the given point with the given number icon and text
function createMarker(p,text) {
var marker = new GMarker(p);
if (text!=""){
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);});
}
return marker;
}
` var geocoder = null;`
` var map = null;`
function load() {//loading the map
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.enableScrollWheelZoom();
geocoder = new GClientGeocoder();
if (init_street!=""){
geocoder.getLatLng(init_street,function(point) {//set center point in map
if (point){
map.setCenter(point, zoom);
map.addOverlay(createMarker(point,init_street));
map.openInfoWindow(point,init_street);
}
});
}
map.addControl(new GLargeMapControl());
map.setMapType(G_NORMAL_MAP);
}
}`
function(data, responseCode) {
if(responseCode == 200) {
var texts = [];
var addresses = [];
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("item");
alert (markers.length);
for (var i = 0; i < markers.length; i++) {
var address=markers[i].getElementsByTagName('address').item(0).childNodes.item(0).nodeValue;
if (address!=null){
//alert (address);
var title=markers[i].getElementsByTagName('title').item(0).childNodes.item(0).nodeValue;
var link=markers[i].getElementsByTagName('link').item(0).childNodes.item(0).nodeValue;
var desc=markers[i].getElementsByTagName('description').item(0).childNodes.item(0).nodeValue;
desc=desc.substr(0,220);//limit
addresses.push(address);
texts.push("<div style='width: 200px'><a target='_blank' href='" +link+"'>"+title+"</a><br />"+desc+"</div>");
}//if
}//for
for (var i = 0; i < addresses.length; i++) {
geocoder.getLatLng(addresses[i], function (current) {
return function(point) {
if (point) map.addOverlay(createMarker(point,texts[current]));
}
}(i));
}
}//if });
I Understand the issue of needing a callback function to load the markers, but Im lost..
Any help apreciated!! ;)
Thx in advanced!!
This usually happens when fetching data with Ajax or similar. Basically when you fetch the data you need to utilize a callback function to wait for the data. If you don't there is no data to execute on. However, if you pause the execution with a alert() the data will have been fetched in the background.
Think of it as the waiting for the DOM to load before executing Javascript on the page.
I can't give you a better answer as you have not included the code that is calling the function you included.

Google Map Integrated with Salesforce is Blank

I followed the example code line by line from:
How do I integrate Salesforce with Google Maps?
I am not receiving any errors but my Map is blank. The map displays the zoom and position toggle but nothing else.
Any ideas on why?
Here is my Controller Code and Page Code Below
public class mapController2 {
public String address {get;set;}
private List<Account> accounts;
public void find() {
// Normal, ugly query.
/* address = 'USA';
String addr = '%' + address + '%';
accounts = [SELECT Id, Name, BillingStreet, BillingCity, BillingCountry FROM Account
//WHERE Name LIKE :addr OR BillingStreet LIKE :addr OR BillingCity LIKE :addr OR BillingCountry LIKE :addr];
WHERE BillingCountry LIKE :addr];*/
// address = 'Austin';
String addr = '*' + address + '*';
// Or maybe a bit better full-text search query.
List<List<SObject>> searchList = [FIND :addr IN ALL FIELDS RETURNING
Account (Id, Name, BillingStreet, BillingCity, BillingState, BillingCountry)];
accounts = (List<Account>)searchList[0];
}
public List<Account> getAccounts() {
return accounts;
}
}
Page Code
<apex:page controller="mapController2" tabStyle="Account">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
#map {
height:350px;
}
</style>
</head>
<apex:form >
<apex:pageBlock title="Search by Address">
<apex:inputText value="{!address}"/>
<apex:commandButton value="Search" action="{!find}"/>
<p>Examples: "USA", "Singapore", "Uni", "(336) 222-7000".
Any text data (free text, not picklists, checkboxes etc.) will do.
</p>
</apex:pageBlock>
<apex:pageBlock title="Matching Accounts" rendered="{!address != null}">
<apex:pageBlockTable value="{!accounts}" var="account" id="accountTable">
<apex:column >
<apex:facet name="header"><b>Name</b></apex:facet>
<apex:outputLink value="../{!account.Id}">{!account.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header"><b>Address</b></apex:facet>
{!account.BillingStreet}, {!account.BillingCity}, {!account.BillingCountry}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title="Map" rendered="{!address != null}">
<div id="log"></div>
<p>Tip: hover mouse over marker to see the Account name. Click to show the baloon.</p>
<div id="map">Placeholder - map will be created here.</div>
<script type="text/javascript">
// First we need to extract Account data (name and address) from HTML into JavaScript variables.
var names = new Array();
var addresses = new Array();
var htmlTable = document.getElementById('j_id0:j_id2:j_id7:accountTable').getElementsByTagName("tbody")[0].getElementsByTagName("tr");
for (var i = 0; i < htmlTable.length; ++i) {
names.push(htmlTable[i].getElementsByTagName("td")[0]);
// We need to sanitize addresses a bit (remove newlines and extra spaces).
var address = htmlTable[i].getElementsByTagName("td")[1].innerHTML;
addresses.push(address.replace(/\n/g, "").replace(/^\s+/,"").replace(/\s+$/,""));
}
var coordinates = new Array(); // Array of latitude/longitude coordinates.
var markers = new Array(); // Red things we pin to the map.
var baloons = new Array(); // Comic-like baloons that can float over markers.
var counter = 0;
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
if(addresses.length > 0) {
geocodeOneAddress();
}
function geocodeOneAddress(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: addresses[counter]}, processGeocodingResults);
}
function processGeocodingResults(results, status) {
++counter;
if (status == google.maps.GeocoderStatus.OK) {
coordinates.push(results[0].geometry.location);
} else {
logError(addresses[counter] + " could not be found, reason: " + status);
}
if(counter == addresses.length) {
finalizeDrawingMap();
} else {
geocodeOneAddress();
}
}
function finalizeDrawingMap() {
// Compute min/max latitude and longitude so we know where is the best place to center map & zoom.
var minLat = coordinates[0].b;
var maxLat = coordinates[0].b;
var minLong = coordinates[0].c;
var maxLong = coordinates[0].c;
for(i=0;i < coordinates.length; i++){
markers.push(new google.maps.Marker({ position: coordinates[i], map: map, title: names[i].getElementsByTagName("a")[0].innerHTML, zIndex:i}));
baloons.push(new google.maps.InfoWindow({content: '<b>'+names[i].innerHTML + '</b><br/>' + addresses[i]}));
google.maps.event.addListener(markers[i], 'click', function() {
baloons[this.zIndex].open(map,this);
});
minLat = Math.min(minLat, coordinates[i].b);
maxLat = Math.max(maxLat, coordinates[i].b);
minLong = Math.min(minLong, coordinates[i].c);
maxLong = Math.max(maxLong, coordinates[i].c);
}
map.setCenter(new google.maps.LatLng(minLat + (maxLat-minLat) / 2, minLong + (maxLong-minLong) / 2));
// All that is left is to possibly change the zoom. Let us compute the size of our rectangle.
// This is just a rough indication calculation of size of rectangle that covers all addresses.
var size = (maxLat-minLat) * (maxLong-minLong);
var zoom = 13;
if(size > 7100) {
zoom = 2;
}
else if(size > 6000) {
zoom = 3;
}
else if(size > 550) {
zoom = 4;
}
else if(size > 20) {
zoom = 6;
}
else if(size > 0.12) {
zoom = 9;
}
map.setZoom(zoom);
}
function logError(msg) {
var pTag = document.createElement("p");
pTag.innerHTML = msg;
document.getElementById('log').appendChild(pTag);
}
</script>
</apex:pageBlock>
</apex:form>
</apex:page>
Ya even I was getting a blank map but try to do
https://c.na3.visual.force.com/apex/map?id=0015000000UsQZR
Make sure you enter a valid account id to use.
<apex:page standardController="Account">
<script src="http://maps.google.com/maps?file=api">
</script>
<script type="text/javascript">
var map = null;
var geocoder = null;
var address = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";
function initialize() {
if(GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("MyMap"));
map.addControl(new GMapTypeControl());
map.addControl(new GLargeMapControl3D());
geocoder = new GClientGeocoder();
geocoder.getLatLng(
address,
function(point) {
if (!point) {
document.getElementById("MyMap").innerHTML = address + " not found";
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.bindInfoWindowHtml("Account Name : <b><i> {!Account.Name} </i></b>
Address : "+address);
}
}
);
}
}
</script>
<div id="MyMap" style="width:100%;height:300px"></div>
<script>
initialize() ;
</script>
</apex:page>
Hope this helps
Thanks
tosha
And use the code given as:
src="http://maps.google.com/maps/api/js?sensor=false"
Use
https
not
http
It will definately be blank in firefox or chrome if using http and not https. Try https.