how to refresh maps with ajax request? - javascript

I want to reload map in ajax call.This code is reloading whole page when i change status it reloads whole page.I want after 10 seconds only map reloads not whole page. if i select on change available then map reloads after every 10 seconds in available option.
i have drivers if i select status of driver available then map shows the drivers which are available. i want to refresh map after 10 sec so that i can see if there is any other driver available. if available then it will show on map without reloading whole page. This is what i want.
i am refreshing content in some div of the page by using jQuery load() function but its not working.
Html:
<div class="row">
<div class="col-md-12">
<div id="map" style="height: 550px;">
<div id="time">
<?php echo date('H:i:s');?>
</div>
</div>
</div>
</div>
Script:
$('#status').change(function () {
var job_status = $(this).val();
$.ajax({
url: '{{ URL::to('/get_drivers/')}}' + '/' + $(this).val(),
type: 'get',
datatype: 'json',
success: function (response) {
setInterval("my_function();", 10000);
function my_function() {
$('#map').load(location.href + ' #time');
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 31.5204, lng: 74.3587},
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
{{--var carIcon = '{{asset('images/red-car.png')}}';--}}
if (gmarkers.length > 0) {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) {
gmarkers[i].setMap(null);
} else {
gmarkers[i].getMap();
gmarkers[i].setMap(map);
}
}
gmarkers = [];
}
for (i = 0; i < locationData.length; i++) {
if (job_status == 8) {
if (job_status === '') {
gmarkers = [];
}
else {
for (i = 0; i < locationData2.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationData2[i]['driver_lat'], locationData2[i]['driver_long']),
map: map,
optimized: false,
icon: '{{asset('images/grey-car.png')}}'
});
google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
return function () {
infowindow.setContent('<h6><b>' + locationData2[i]['first_name'] + '</h6>');
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, 'click', (function (marker, i) {
return function () {
infowindow.setContent();
infowindow.close(marker);
}
})(marker, i));
// Push your newly created marker into the array:
gmarkers.push(marker);
var myoverlay = new google.maps.OverlayView();
myoverlay.draw = function () {
// add an id to the layer that includes all the markers so you can use it in CSS
this.getPanes().markerLayer.id = 'markerLayer';
};
myoverlay.setMap(map);
}
}
}
});

You do not need to renew the whole map but drivers markers only (or to be even more precise - not whole markers but their positions only)
I use google own example and put there couple of markers which positions get renewed to random location every second.
//random locations
var latArr = [-20.363882, -21.363882, -22.363882, -23.363882, -24.363882, -25.363882, -26.363882, -27.363882, -28.363882, -29.363882];
var lngArr = [125.044922, 126.044922, 127.044922, 128.044922, 129.044922, 130.044922, 131.044922, 132.044922, 133.044922, 134.044922];
//global array to hold all markers
var markersArr = [];
//map init from google example
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922}
});
//create markers
var marker1 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: true,
map: map
});
var marker2 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
draggable: true,
map: map
});
markersArr.push(marker1);
markersArr.push(marker2);
}
//function to change markers locations
function renewMarkers(){
for(i=0; i<markersArr.length; i++){
var lt = Math.floor(Math.random()*10);
var ln = Math.floor(Math.random()*10);
markersArr[i].setPosition({lat: latArr[lt], lng: lngArr[ln]})
}
}
setInterval(renewMarkers, 1000);
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
<div id="map"></div>

Related

Cannot remove markers from google maps api

The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}

How to open web links from some Google Maps markers?

I can open web link from marker by
google.maps.event.addListener(marker, "click", function() {
window.open('http://example.com/');
});
But what if I need to place 100 markers with 100 links to Google Maps?
My array with coordinates and links looks like this
var point = [[52.7081444444445, 58.6677361111111, "Sib/2377/index.html"],
[52.7039611111111, 58.668425, "Sib/2378/index.html"],
[52.6993166666667, 58.6680305555556, "Sib/2379/index.html"],
[52.6946277777778, 58.6679416666667, "Sib/2380/index.html"],
[52.6947833333333, 58.6755555555556, "Sib/2381/index.html"]];
add the URL as a property of the marker (.url). Open the window using this.url
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: -33.9,
lng: 151.2
}
});
setMarkers(map);
}
// Data for the markers consisting of a Latitude, a Longitude and a URL.
var points = [
[52.7081444444445, 58.6677361111111, "http://www.google.com"],
[52.7039611111111, 58.668425, "http://www.yahoo.com"],
[52.6993166666667, 58.6680305555556, "http://maps.google.com"],
[52.6946277777778, 58.6679416666667, "http://maps.google.com?q=52.6946277777778,58.6679416666667"],
[52.6947833333333, 58.6755555555556, "http://maps.google.com?q=52.6947833333333,58.6755555555556"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

javascript function that takes parameter is called on page load

for(i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker ({
position: locations[i][0],
map: map,
label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
mapMarkers[i].addListener('click', markerClick(currentLocation));
}
function markerClick(location) {
console.log("you clicked " + location)
}
The function markerClick is being called each time it is added to an element. How can i make it so it is only called when the element is clicked? i read in another answer herethat leaving out the () would fix this, but I need to pass a paramater and am not sure how to do this. thanks for any help
One option would be for your markerClick function to return a function.
function markerClick(location) {
return function(evt) {
console.log("you clicked " + JSON.stringify(location));
}
}
proof of concept fiddle
code snippet:
var locations = [
[{lat: 42, lng: -72}, "Here"],
[{lat: 42.1,lng: -72.1}, "There"]
];
var mapMarkers = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(42, -72),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker({
position: locations[i][0],
map: map,
// label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
mapMarkers[i].addListener('click', markerClick(currentLocation));
}
}
function markerClick(location) {
return function(evt) {
console.log("you clicked " + JSON.stringify(location));
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
When you add the listener, you're calling the markerClick() function rather passing it as a variable. Here's how to fix it:
//using a separate function like this avoids some nasty
//problems with callbacks and closures in for loops
function addMapMarkerClickListener( mapMarker, location ) {
//we use an anonymous function as the listener
mapMarker.addListener('click', function() {
markerClick( location );
});
}
for(i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker ({
position: locations[i][0],
map: map,
label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
addMapMarkerClickListener( mapMarkers[i], currentLocation );
}
function markerClick(location) {
console.log("you clicked " + location)
}

google maps v3: how to drop markers, remove, loop again

I have been studying Google Maps and I would like to accomplish the following goal:
1) drop markers one by one;
2) delete last marker (so just one is in viewport)
3) drop next marker
4) Have info window opened in each marker
5) repeat operation
I have been trying to twist the code for animations AND trying to set map null (setMap(null)), but with no success after calling the drop function. Any suggestion on how to do that?
Bottom line: have something like this. Of course this has one big extra step of difficult, which is pulling data from database.
Here is the code.
Any help will be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker animations with <code>setTimeout()</code></title>
<style>
#map-canvas{
width:600px;
height:600px;
position: "absolute";
top: 0px;
left: 0px;
overflow: "hidden";
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var berlin = new google.maps.LatLng(52.520816, 13.410186);
var neighborhoods = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)
];
var markers = [];
var iterator = 0;
var Marker;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
drop();
}
function drop(){
for (var i = 0; i < neighborhoods.length; i++) {
var m = neighborhoods[i];
(function(n){
setTimeout(function() {
addMarker(n);
}, i * 500);
}(m));
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html
>
Did you want only one marker to display at a time?
Here is some code that does that:
$(function() {
var BERLIN = new google.maps.LatLng(52.520816, 13.410186);
var NEIGBORHOODS = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)];
var map = null;
var marker = null;
var index = 0;
var infoWindow = null;
function createMap() {
return new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: BERLIN,
zoom: 12
});
}
function dropMarker(map, pos) {
return new google.maps.Marker({
map: map,
position: pos,
draggable: false,
animation: google.maps.Animation.DROP
});
}
function changeMarker() {
if (marker) {
infoWindow.close();
marker.setMap(null);
}
var pos = NEIGBORHOODS[index];
marker = dropMarker(map, pos);
infoWindow.setContent('lat: ' + pos.lat() + '<br />' + 'lng: ' + pos.lng());
setTimeout(function () {
infoWindow.open(map, marker);
}, 500);
index = (index + 1) % NEIGBORHOODS.length;
setTimeout(function () {
changeMarker();
}, 2000);
}
map = createMap();
infoWindow = new google.maps.InfoWindow()
changeMarker();
});
Notice how the changeMarker() function does its work, then usessetTimeout() to call itself again. This sets up an infinite loop where changeMarker() is called every two seconds.
I used setTimeout() to delay the showing of the Info Window by a half second so it does not appear until the drop is finished.
jsfiddle demo

Google Maps api v3 - "Infowindow not defined" Error

The map comes up and the point appears. I have the title appearing as well. But as soon as I click on the marker to get info, nothing appears. Firebug info is below.
The information is being brought in via a database and there are multiple items; multiple markers are shown on the map as they should.
Any help would be apprecaited. Thanks..
Firebug Point Info:
MarkLat[i] = xx.xxxxxxxxxxxxxx;
MarkLong[i] = -xx.xxxxxxxxxxxxxx;
MarkerTitle[i] = 'Title 1';
Display[i] = '<table><tr><td>Title 1</td></tr><tr><td>Title 1 Address<br />Title 1 City, State Zip</td></tr><tr><td>Title 1 Phone</td></tr><tr><td>Title 1 Email</td></tr><tr><td>Title 1 URL</td></tr></table>';
Firebug Error:
infowindow is not defined
infowindow.open(map,marker);
Code:
<script type="text/javascript">
var i = -1;
var MarkLat=new Array();
var MarkLong=new Array();
var MarkerTitle=new Array();
var Display=new Array();
var MapCenter = new google.maps.LatLng(xx.xxxxxxxxxxxxxx,-xx.xxxxxxxxxxxxxx)
</script>
<script type="text/javascript">
var i = i + 1;
MarkLat[i] = [[Lat]];
MarkLong[i] = [[Long]];
MarkerTitle[i] = '[[Title]]';
Display[i] = '<table><tr><td>[[Title]]</td></tr><tr><td>[[Address]]<br />[[City]], [[State]] [[Zip]]</td></tr><tr><td>[[Phone]]</td></tr><tr><td>[[Email]]</td></tr><tr><td>[[WebURL]]</td></tr></table>';
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 12,
center: MapCenter,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
for (var i = 0, length = 50; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addDomListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Changing to a capital W was not enough for me. Only one location was being opened. I tested your code with two points:
MarkLat = [];
MarkLong = [];
Display = [];
MarkerTitle= [];
MarkLat[0] = 0;
MarkLong[0] = 0;
Display[0] = { content: "hi" };
MarkerTitle[0] = "hello";
MarkLat[1] = 10;
MarkLong[1] = 10;
Display[1] = { content: "hi 2" };
MarkerTitle[1] = "hello 2";
I'm guessing you only want one InfoWindow on the screen at any given time. Then, a single InfoWindow should be declared, with the contents kept inside the marker, and have the contents change as the marker is clicked.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i],
infoWindowContent: Display[i]
});
// Notice I used the 'this' keyword inside the listener
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(this.infoWindowContent.content);
infoWindow.open(map,this);
});
}
The alternative, having many InfoWindows pop up, needs a change to click listener, so that a reference to each individual InfoWindow is preserved. This effect is accomplished with an anonymous function wrapped around the infoWindow.open function (a new function scope is created).
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addListener(marker, 'click', (function(infoWindow) {
return function() {
infoWindow.open(map,this);
}
})(infoWindow));
}
infowindow != infoWindow
You just have declared it with a capital, trying to use it without

Categories

Resources