How to clear out the google map markers? - javascript

Each time my code invokes the function search() I would like the google map markers that were placed on the map from the previous search call cleared off the map and the NEW markers placed on the map.
I need help clearing out the markers.
function search() {
//loading the map with markers
$('.map').addClass('.map-with-searching');
$.ajax({
url: 'https://' + getApiURL(),
data: data,
contentType: 'application/json',
type: 'POST',
success: function (result) {
$('#universitiesList').html('');
for (const row of result.payload) {
locations.push({ lat: row.location.latitude, lng:
row.location.longitude, university: row.campusName, id:row.campusID});
}
//marker.setVisible(false);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: { lat: locations[i].lat, lng: locations[i].lng },
map: map,
data: {
university: locations[i].university,
id: locations[i].id,
name: locations[i].name,
address: locations[i].address,
image: locations[i].image,
}
});
map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));
marker.addListener('click', function () {
if (!this.infoWindow) {
this.infoWindow = new google.maps.InfoWindow({
content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="'
+ this.data.image + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
});
}
this.infoWindow.open(map, this);
})
};
},
error: function (jqXhr, textStatus, errorThrown) {
//console.log(errorThrown);
}
})
}

Here's an untested example - store references to the markers and then call .setMap(null) to remove them from the map.
// an array of the markers on the map
let markers = [];
function search() {
// clear the markers
for( const marker of markers ) {
marker.setMap(null);
}
markers = [];
//loading the map with markers
$('.map').addClass('.map-with-searching');
$.ajax({
url: 'https://' + getApiURL(),
data: data,
contentType: 'application/json',
type: 'POST',
success: function (result) {
$('#universitiesList').html('');
for (const row of result.payload) {
locations.push({ lat: row.location.latitude, lng: row.location.longitude, university: row.campusName, id:row.campusID});
}
//marker.setVisible(false);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: { lat: locations[i].lat, lng: locations[i].lng },
map: map,
data: {
university: locations[i].university,
id: locations[i].id,
name: locations[i].name,
address: locations[i].address,
image: locations[i].image,
}
});
// Store a reference so you can remove markers later
markers.push( marker );
map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));
marker.addListener('click', function () {
if (!this.infoWindow) {
this.infoWindow = new google.maps.InfoWindow({
content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="' + this.data.image + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
});
}
this.infoWindow.open(map, this);
});
};
},
error: function (jqXhr, textStatus, errorThrown) {
//console.log(errorThrown);
}
});
}

Related

page call ajax another subpage and this subpage call another subpage?

I have 3 page: page1.php page2.php page3.php
page1.php has ajax and is calling page2.php.
page2.php has php and javascript code and if everything is correct ajax calls page3.php that registers everything in mysql.
There is only one problem. I think an ajax call to a sub page, this sub page cannot call another sub page is it correct?
Each separate page works wonders.
but page2.php is not able to call by ajax when it is called by ajax.
page1.php
<script>
var x = document.getElementById("demo");
function getLocation6() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition6, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition6(position) {
var latfinal=position.coords.latitude;
var longfinal=position.coords.longitude;
var latlng = new google.maps.LatLng(latfinal, longfinal);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var Var_JavaScript = results[1].formatted_address;
$.ajax({
type: "POST",
url: "insert-fichaje2.php?lat="+latfinal+"&long="+longfinal+"&status=ReanudarTransporte&usuario=<?php echo htmlspecialchars($_SESSION["username"]); ?>&direccion="+Var_JavaScript +"&empresa=<?php echo $empresa;?>",
dataType: "json",
success: function() {
$.ajax({
type: "POST",
url: "page2.php?lat="+latfinal+"&long="+longfinal+"&status=ReanudarTransporte&usuario=<?php echo htmlspecialchars($_SESSION["username"]); ?>&direccion="+Var_JavaScript +"&empresa=<?php echo $empresa;?>",
dataType: "json",
});
alert("Cambio con exito!");
location.reload();
},
error: function() {
alert(" ERROR!!!");
location.reload();
}
});
}
}
});
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude + "";
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("Has detenido acceso a tu ubicacion. Porfavor dame permiso a tu ubicacion!");
x.innerHTML = "Has detenido acceso a tu ubicacion. Porfavor dame permiso a tu ubicacion."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "No tengo tu ubicacion"
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "A aparesido un error."
break;
}
}
</script>
page2.php intenta ver si la ubicacion esta dentro de los circulos permitido y va llamar a otra pagina para introducir si es o no dentro del circulo.
<script>
window.onload = function init() {
var monitorzonafichaje = "<?php echo $avisosficahejzonas;?>";
var monitorzonanave = "<?php echo $fichajefueranave;?>";
var monitorzonapunctos = "<?php echo $fichajefuerapunctos;?>";
var latempresa= "<?php echo $latempresa;?>";
var longempresa= "<?php echo $longempresa;?>";
var latuser ="<?php echo $lat;?>";
var longuser = "<?php echo $long;?>";
if (monitorzonafichaje === "1"){
if (monitorzonanave === "1"){
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentCenter2 = '<span class="infowin">Center2 Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(latempresa, longempresa),
latLngCMarker = new google.maps.LatLng(latempresa, longempresa),
latLngCMarker2 = new google.maps.LatLng(38.0814, -93.5105),
latLngA = new google.maps.LatLng(latuser, longuser),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Location',
map: map,
draggable: true
}),
markerCenter2 = new google.maps.Marker({
position: latLngCMarker2,
title: 'Location',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'Location',
map: map,
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'Location',
map: map,
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
circle2 = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
circle2.bindTo('center', markerCenter2, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
bounds2 = circle2.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
var myvar = bounds.contains(latLngA);
if (!myvar){
$.ajax({
type: "POST",
url: "page3.php?dentro=no",
dataType: "json",
});
}else{
$.ajax({
type: "POST",
url: "page3.php?dentro=yes",
dataType: "json",
});
}
//--------
}else{
if (monitorzonapunctos === "1"){
}
}
}
};
</script>
and page3.php is php insert mysql.

javascript function before google maps load

I have to put markes on google maps, but the array with lat, long is made by an Ajax request.
Map is loaded before the initialization of the array and I don't see the markers.
I think that this is the problem but I'm not so sure. hope you can help me
<script>
$(document).ready(function() {
setVariable('<?php echo $_SESSION["token"]?>');
});
</script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">
</script>
coord = new Array();
function setVariable(token) {
format="text/plain";
$.ajax({
url: BASE_URL + "reports",
type: "GET",
contentType: "application/json; charset=utf-8",
headers: {'x-access-token': token},
cache: false,
success: function(data){
if (data.success){
$.each(data.data.reports, function (i, item) {
coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
});
console.log(coord)
}else{
alert(data.error.message);
}
},
error: function(data){
console.log(data);
}
});
}
function initMap() {
var myLatLng = {lat: 43.1107168, lng: 12.3908279};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: myLatLng
});
var marker, i;
for (i = 0; i < coord.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(coord[i][0], coord[i][1]),
map: map,
title: 'Hello World!'
});
}
}
How can i resolve this?
thank you very much.
You will need to restructure the code in order to make this work. We need to add markers on the map only after we have fetched the lat/long data successfully by making an AJAX request. We could do this in the following manner.
<script defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">
/*
We will keep a global variable that would contain a reference to the google map object.
It would be initialized as soon as the script for google maps is loaded and initMap function is called subsequently.
*/
var GoogleMap;
coord = new Array();
function setVariable(token) {
format="text/plain";
$.ajax({
url: BASE_URL + "reports",
type: "GET",
contentType: "application/json; charset=utf-8",
headers: {'x-access-token': token},
cache: false,
success: function(data){
if (data.success){
$.each(data.data.reports, function (i, item) {
coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
});
console.log(coord)
var marker, i;
for (i = 0; i < coord.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(coord[i][0], coord[i][1]),
map: GoogleMap,
title: 'Hello World!'
});
}
}else{
alert(data.error.message);
}
},
error: function(data){
console.log(data);
}
});
}
function initMap() {
var myLatLng = {lat: 43.1107168, lng: 12.3908279};
GoogleMap = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: myLatLng
});
}
Hopefully, this should work!

Getting response in network but console return error with cross origin

I'm using google map api for web...
Also I'm calling search nearby api directly from jquery to search places,
this is error in console
this is response in network
I've already added to use api from all referrer in google api console.
var param = {
key: "My_Key",
location: pos.lat+','+pos.lng,
radius: 3000,
type: "church"
};
$.ajax({
url: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + jQuery.param(param),
method: "GET",
async: false,
success: function(resp) {
console.log(resp);
},
error: function(error) {
console.log(error);
}
});
Don't use the Places API web service from javascript on the client, use the Google Maps Javascript API v3 Places Library.
example in documentation
proof of concept fiddle (using the posted request parameters)
code snippet:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '3000',
type: ['church']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map"></div>
Try adding dataType : 'jsonp' in your $.ajax call as,
$.ajax({
url: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + jQuery.param(param),
method: "GET",
dataType : 'jsonp',
async: false,
success: function(resp) {
console.log(resp);
},
error: function(error) {
console.log(error);
}
});
Hope this helps!

Markers not being drawn on map

I've written the below code and all is working grand from the point of view of data, the data is returned from the ajax call in JSON format like the snippet below.
The problem seems to be with the addMarker function, the data is passed into the function ok, I've verified this with an alert() from within the addMarker function but no markers are being plotted on the map and no errors are being thrown in the browser or console.
Do I need to call setMapOnAll after each marker is added to display it on the map? I've tried adding setMapOnAll to the end of the addMarker function but nothing changed.
JSON:
{id:278, title:"", lat:"52.50474200", lng:"-8.71032700"}
Javascript:
$(document).ready(function () {
var map;
var markers = [];
function loadMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
minZoom: 2,
maxZoom: 12,
zoom: 6,
disableDefaultUI: true,
zoomControl: true
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
} else {
map.setCenter({lat: -34.397, lng: 150.644});
}
loadMarkerData(-1);
}
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
map: map
});
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function loadMarkerData(selectedKeys, year, source)
{
var data = {id: 1};
if (selectedKeys != '' && year != '' && source != '') {
data = {id: 1, selectedKeys:selectedKeys, year:year, source:source};
}
$.ajax(
{
url: "ajaxcall.php",
type: "POST",
data: data,
success: function (data, textStatus, jqXHR)
{
if (data != '') {
markerObj = eval(data);
$.each(markerObj, function(index, element) {
addMarker(element.lat, element.lng)
});
}
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
});
With your original code, I get a javascript error: Assertion failed: InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number, because those values are strings. You can fix that by changing this:
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
map: map
});
markers.push(marker);
}
To:
function addMarker(lat, lng) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(lat),
lng: parseFloat(lng)
},
map: map
});
markers.push(marker);
}

Uncaught exception when calling Google maps directionsService

I am getting an Uncaught InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object error when I call the Google maps directions service - even so, the directions seem to be added to the map?
Here is the function that calls the directions service between the current location (currentPos) and a location not too far away (LatLng(52.705151, -2.741861))
function calcRoute() {
var start = currentPos;
var end = new google.maps.LatLng(52.705151, -2.741861);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Here is the code that initializes the map and calls the calcRoute() function:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var currentPos;
var destinationPos;
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var infoWindow = new google.maps.InfoWindow();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currentPos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: currentPos,
map: map,
title: "You are here"
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
map.setCenter(currentPos);
$.ajax({
type: 'GET',
url: $('#AddMarkersToMap').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
addMarkers(data, infoWindow);
},
error: function () {
alert("Error");
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
calcRoute();
}
Some Googling suggested the exception might be caused because the map hadn't loaded so I tried putting the calcRoute call like this which didn't help:
$(function () {
calcRoute()
});
Your currentPos variable is undefined when you call calcRoute.
getCurrentPosition is asynchronous and will not have executed before calcRoute and therefore not set currentPos.
If you need to use currentPos in calcRoute you should call it in the callback to getCurrentPosition to ensure that it is defined.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currentPos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: currentPos,
map: map,
title: "You are here"
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
map.setCenter(currentPos);
$.ajax({
type: 'GET',
url: $('#AddMarkersToMap').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
addMarkers(data, infoWindow);
},
error: function () {
alert("Error");
}
});
calcRoute();
//\\//\\//\\
}, function () {
handleNoGeolocation(true);
});

Categories