Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>
Related
We want to make the following search box GET a page named /listings when a users types something in it and hits enter. Does anyone had any ideas on how to do this?
Many Thanks!
$(function() {
var autocomplete;
var geocoder;
var input = document.getElementById('location');
var options = {
componentRestrictions: {
'country': 'us'
},
types: ['(regions)'] // (cities)
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$('#go').click(function() {
var location = autocomplete.getPlace();
geocoder = new google.maps.Geocoder();
console.log(location['geometry'])
lat = location['geometry']['location']['J'];
lng = location['geometry']['location']['M'];
var latlng = new google.maps.LatLng(lat, lng);
// http://stackoverflow.com/a/5341468
geocoder.geocode({
'latLng': latlng
}, function(results) {
for (i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].address_components.length; j++) {
for (var k = 0; k < results[i].address_components[j].types.length; k++) {
if (results[i].address_components[j].types[k] == "postal_code") {
zipcode = results[i].address_components[j].short_name;
$('span.zip').html(zipcode);
}
}
}
}
});
});
});
<input type="text" id="location" name="location" placeholder="City or ZIP Code" />
<span class="zip"></span>
The easiest way would be to register a listener for the change event on your input:
$('#location').change(function() {
$.get('./listings', function(data) {
// data is the content from '/listings'
});
});
If you want to load the contents from the listings page into a specific element, you can use jQuery.load:
$('#location').change(function() {
// loads the html content of listings into your element
// after the user changes the value of #location input
$( "your-element-selector" ).load("/listings");
});
Or if you want to navigate to the your-page/listings in the browser, you can take a look at this question
I first read a sets of coordinates in my local drive, then put them in
the xcoord and y coord to be start,waypts,destination which will be plotted on Google Map.
But i discovered that, once the coodinates exceeding a certain number,the route is not plotted anymore,but a road map without and route. changing travelmode also changing the number of effective waypoints. What can be done when i have >100 coordinates to be plotted? Also, i would like to change all the marker into default one but not the green one with letters on it.(After 26 points the marker become normal again.) Thank you very much.
I was first using the example provided in a question about 8 waypoints, which is here:
Plotting more than 8 waypoints in Google Maps v3
My code are as follow:
xcoord = [];
ycoord = [];
stops = [] ;
document.getElementById('file').onchange = function(){
alert('4');
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
//alert(lines[line]);
var split = [];
split = lines[line].split(',');
window.xcoord.push(split[0]);
window.ycoord.push(split[1]);
}
alert('finish');
}
reader.readAsText(file);
};
jQuery(function() {
document.getElementById('button').onclick = function initMap(){
for(i = 0;i<xcoord.length;i++){
window.stops.push({"Geometry":{"Latitude":xcoord[i],"Longitude":ycoord[i]}});}
var map = new window.google.maps.Map(document.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer();
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);}});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(22.2830, 114.200),
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
// alert(legs.length);
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,"marker"+i,"some text for the "+i+"marker<br>"+legs[legs.length-1].end_address,markerletter);
}
}
});
})(k);
}
}
};
}
The Snap to road thing is done via loading coordinates using PHP and then
using the google api. the code is as follow(for less than 200 points):
<!DOCTYPE html>
<?php
$stringJoin = "";
$stringJoin2 = "";
$index = 0;
$handle = fopen($_GET['fileName'], "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$index++;
if ($index ==99 ){
$stringJoin2 .= trim($line)."|";
}
if ($index >= 100) {
$stringJoin2 .= trim($line)."|";
if($index == 200){
break;
}
continue;
}
$stringJoin .= trim($line)."|";
}
fclose($handle); }
echo $index;
echo "<br>";
$stringJoin = substr($stringJoin, 0, -1);
$stringJoin2 = substr($stringJoin2, 0, -1);
echo $stringJoin;
echo "<br>";
echo $stringJoin2; ?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="button" name="button" id="button">
<input type="file" name="file" id="file">
<div id="map"></div>
<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>
var apiKey = 'AIzaSyCk5PjtR_spPKrVowRS3A7I3IE4gX6Ctec';
var map;
var drawingManager;
var placeIdArray = [];
var placeIdArray2 = [];
var polylines = [];
var polylines2 = [];
var snappedCoordinates = [];
var snappedCoordinates2 = [];
document.getElementById('button').onclick = function initialize() {
alert("Start");
var mapOptions = {
zoom: 13,
center: {lat: 22.3030, lng: 114.200} };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
runSnapToRoad();
runSnapToRoad2();}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad() {
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: <?php echo '"'.$stringJoin.'"';?>}, 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);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId); }}
// 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);}
</script>
<div id="bar">
<p class="auto"><input type="text" id="autoc"/></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
I want a condition on my code where user input start point and end point, I want to make a check on start point to check that it is located in London or not so I find this code which work well in function but I want its variable town make function outside of this function so I create the checkpoint.
var input = document.getElementById('start');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// get town of selected place
function getTown(address_components) {
var geocoder = new google.maps.Geocoder(); result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
var town = getTown(place.address_components);
// if place is in London, move marker to the place
if (town == 'London') {
alert('in London');
} else {
// if not, do nothing and alert user
alert('you must click on a place in London');
}
});
How can I access var town outside of this function on whole page so I make condition on base of it?
You can make a variable outside of the scope of the callback to set the result to.
var input = document.getElementById('start');
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {lat: 51.507351, lng: -0.127758}
});
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var town;
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
function getTown(address_components) {
result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
document.getElementById('place').innerHTML = '';
document.getElementById('town').innerHTML = '';
town = getTown(autocomplete.getPlace().address_components);
});
function inLondonCheck(placeName) {
document.getElementById('place').innerHTML = placeName + " in London? " + (town === 'London');
document.getElementById('town').innerHTML = town || '';
}
setInterval(function() {
if (town) inLondonCheck(autocomplete.getPlace().name);
}, 500);
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="start">
<div>Place<pre id="place"></pre></div>
<div>Town<pre id="town"></pre></div>
<div id="map-canvas"></div>
I want to add new markers after removing markers from Google maps. However, my code isn't doing what I expected. After the removal, no new marker could be added.
Code snippet:
function codeAddress(coordinates) {
console.log("called");
var myLatlng = new google.maps.LatLng(coordinates.lb,coordinates.mb);
var marker = new google.maps.Marker({
map: map,
position: myLatlng
});
markersArray[markerid] = marker;
markerid++;
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
markersArray = {};
markerid = 0;
}
function go(){
var cMin = document.getElementById('costMin').value;
var cMax = document.getElementById('costMax').value;
var religion = document.getElementById('religion').value;
// remove previous marker layer
deleteOverlays();
console.log(coorList.length);
for(var i = 0; i < coorList.length; ++i){
//codeAddress();
if(religion != ""){
if(coorList[i].cost1 >= cMin && coorList[i].cost1 <= cMax && coorList[i].religion.toLowerCase() ==religion.toLowerCase()){
codeAddress(coorList[i]);
}
}
else{
if(coorList[i].cost1 >= cMin && coorList[i].cost1 <= cMax){
codeAddress(coorList[i]);
}
}
}
}
<input id="costMin" type="textbox" >
<input id="costMax" type="textbox" >
<input id="religion" type="textbox" >
<input type="button" value="Go" onclick="go();">
When I placed a console.log("called") within the codeAddress() function, it seems like the function is not called at all after the click. If I get rid of deleteOverlays() from the go() function, the codeAddress will be called. Is there anything wrong with my code?
I have put some markers for specific locations in a map, and I have two buttons, one to hide all the markers (clearOverlays) and other to show them again (showOverlays) but it isn't working. In my JavaScript console I am getting this error : Cannot call method 'setMap' of undefined
Here's my code..
// COORDENADAS
var coordenadas = [
['Punto 1', 19.558061,-99.296344, 4],
['Punto 2', 19.55886, -99.296886, 5],
['Punto 3',19.559103, -99.296688, 3],
['Punto 4', 19.560164,-99.297347, 2],
['Punto 5',19.560073,-99.296064, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng( 19.561883, -99.298287),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var ventana = new google.maps.InfoWindow();
var marcador, i;
for (i = 0; i < coordenadas.length; i++) {
marcador = new google.maps.Marker
({
position: new google.maps.LatLng(coordenadas[i][1], coordenadas[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(
marcador, 'mouseover', (function(marcador, i) {
return function() {
ventana.setContent(coordenadas[i][0]);
ventana.open(map, marcador);
}
})(marcador, i)
);
}
function clearOverlays(map) {
for (var i = 0; i < coordenadas.length; i++) {
marcador[i].setMap(null);
}
setAllMap(null);
console.log('click Ocultar');
}
function showOverlays(map) {
for (var i = 0; i < coordenadas.length; i++) {
marcador[i].setMap(map);
}
setAllMap(map);
console.log('click Mostar');
}
marcador is not an array. marcador[i] doesn't exist. That gives the error message: Cannot call method 'setMap' of undefined
You need an array of google.maps.Marker objects.
var gmarkers = [];
function clearOverlays(map) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
function showOverlays(map) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
for (i = 0; i < coordenadas.length; i++) {
var marcador = new google.maps.Marker
({
position: new google.maps.LatLng(coordenadas[i][1], coordenadas[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
gmarkers.push(marcador);
google.maps.event.addListener(
marcador, 'mouseover', (function(marcador, i) {
return function() {
ventana.setContent(coordenadas[i][0]);
ventana.open(map, marcador);
}
})(marcador, i)
);
}
working example