Prevent Onload Infinite Looping - javascript

i have a Question . . How can i Prevent this to infinite loop because im new to Google maps and Jquery.
Ive read alot of Answers but not even one is working
This is my Codes:
<script type="text/javascript">
var geocoder, infoBubble;
var map;
//var mgr;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
codeAddress();
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
infoBubble = new InfoBubble({
map: map,
shadowStyle: 0,
padding: 10,
borderRadius: 10,
arrowSize: 15,
maxWidth: 300,
borderWidth: 1,
borderColor: '#ccc',
arrowPosition: 50,
arrowStyle: 0
});
$.getJSON('/Dashboard/LoadWorkerList', function (address) {
$.each(address, function () {
var currVal = this["AddressLine1"];
var Name = this["Name"];
var Gender = this["Gender"];
var Bdate = this["Birthdate"];
var ID = this["Worker_ID"];
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
var link = $('' + currVal + '')
.data('location', results[0].geometry.location);
$('#places').append($('<li>').append(link));
link.on('click', function (event) {
event.preventDefault();
google.maps.event.trigger(address[0], "click");
infoBubble.removeTab(0);
infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br><br>" + '<center>View Profile</center>');
infoBubble.open(map, marker);
}
);
google.maps.event.addListener(map, 'idle', function () {
$('#places li a').css('display', function () {
return (map.getBounds().contains($(this).data('location')))
? ''
: 'none';
});
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoBubble.removeTab(0);
infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br><br>" + '<center>View Profile</center>');
infoBubble.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
google.maps.event.trigger(map, 'bounds_changed');
});
}
window.onload = function () {
initialize();
}
</script>
I think this is what is causing the items to loop
` window.onload = function () {
initialize();
}`
and this
` google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
codeAddress(); <------- This one`

The call of initialize isn't the reason for a infinite loop, initialize will be called 1 time.
The only reason I see for a infinite loop is codeAddress:
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
when this condition is true, you call codeAddress again what makes no difference, you will get the same result again and again(with a delay of 2 seconds).
You may either:
let /Dashboard/LoadWorkerList return only up to 10 addresses
ommit in the return of /Dashboard/LoadWorkerList the addresses that already have been returned in previous requests
or:
Use a increasing timeout for each call of geocoder.geocode (increase it by 150ms)

Related

how to move markers in google map API?

I want to move 2 markers on the same google map but i can't find the problem in my code. I can move the 1st marker but i can't move the second one, it is possible to move two markers at the same time on the same map?
How i can move 2 markers at the same time?
<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=650, user-scalable=yes">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#mapcanvas {
height: 97%;
}
#info {
width: auto;
margin: 5px;
height: 3%;
}
</style>
<script>
var map;
var latLonList = [
{ lat: 45.54169245190391, lon: -73.53928729891777 },
{ lat: 45.54173002374242, lon: -73.53945091366768 },
{ lat: 45.541743173879944, lon: -73.53949382901192 },
{ lat: 45.541790138631775, lon: -73.53962525725365 },
{ lat: 45.541844617694764, lon: -73.53980496525764 },
{ lat: 45.54189721811927, lon: -73.5399578511715 },
{ lat: 45.54193666840536, lon: -73.5401026904583 },
{ lat: 45.54198363299557, lon: -73.5402475297451 },
{ lat: 45.542068169159045, lon: -73.5405720770359 },
{ lat: 45.54214706946365, lon: -73.54082688689232 },
{ lat: 45.54222221250792, lon: -73.54105487465858 },
{ lat: 45.54226729828628, lon: -73.54119434952736 },
{ lat: 45.54235746973452, lon: -73.54123994708061 },
{ lat: 45.542543447889805, lon: -73.5411112010479 },
{ lat: 45.542718154081314, lon: -73.54099586606026 },
{ lat: 45.54289661683465, lon: -73.54089394211769 },
{ lat: 45.54298866582284, lon: -73.54103341698647 },
{ lat: 45.54308071466031, lon: -73.54133650660515 },
{ lat: 45.543180277518914, lon: -73.5413445532322 },
{ lat: 45.54330050413203, lon: -73.54127749800682 },
{ lat: 45.54337001002545, lon: -73.54111924767494 }
]
$(document).ready(function () {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(43, 0),
};
map = new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var markerTwo = null;
var i = 0;
var j = 1;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function (position) {
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var secondPoint = new google.maps.LatLng(latLonList[j].lat, latLonList[j].lon);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
draggable: true
});
}
if (markerTwo) {
// Marker already created - Move it
markerTwo.setPosition(secondPoint);
}
else {
// Marker does not exist - Create it
markerTwo = new google.maps.Marker({
position: secondPoint,
map: map,
draggable: true
});
}
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 20) {
i = 0
}
else {
i++;
}
}
if (j == 19) {
j = 0
}
else {
j++;
}
autoUpdate();
});//end document ready
</script>
</head>
<body>
<div id="info">trying to update location every 5 secs - new latitude longitude : <span id="coordinates"></span></div>
<div id="mapcanvas">
</div>
</body>
</html>
the answer:
map=new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var marker2 = null ;
var i = 0;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position, pos) {
//var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var myLatlng = new google.maps.LatLng(latLonList[i+1].lat, latLonList[i+1].lon);
if (marker2) {
// Marker already created - Move it
marker2.setPosition(myLatlng);
}
else {
marker2 = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Client 2'
});
}
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
title: 'Client 1'
});
}
// Center the map on the new position
map.setCenter(myLatlng);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 19)
i = 0
else
i++;
}
autoUpdate();
});//end document ready
http://geekonjava.blogspot.in/2014/10/how-to-make-animated-moving-marker-on.html
Follow This link It Will Helps You
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var speed = 0.000005, wait = 1;
var infowindow = null;
var myPano;
var panoClient;
var nextPanoId;
var startLoc = new Array();
startLoc[0] = 'rio claro, trinidad';
startLoc[1] = 'preysal, trinidad';
startLoc[2] = 'san fernando, trinidad';
startLoc[3] = 'couva, trinidad';
var endLoc = new Array();
endLoc[0] = 'princes town, trinidad';
endLoc[1] = 'tabaquite, trinidad';
endLoc[2] = 'mayaro, trinidad';
endLoc[3] = 'arima, trinidad';
var Colors = ["#FF0000", "#00FF00", "#0000FF"];
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'Trinidad and Tobago'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.fitBounds(results[0].geometry.viewport);
});
// setRoutes();
}
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
function setRoutes(){
var directionsDisplay = new Array();
for (var i=0; i< startLoc.length; i++){
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewport: true
}
directionsService = new google.maps.DirectionsService();
var travelMode = google.maps.DirectionsTravelMode.DRIVING;
var request = {
origin: startLoc[i],
destination: endLoc[i],
travelMode: travelMode
};
directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));
}
function makeRouteCallback(routeNum,disp){
if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
startAnimation(routeNum);
return;
}
return function(response, status){
if (status == google.maps.DirectionsStatus.OK){
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation[routeNum] = new Object();
endLocation[routeNum] = new Object();
polyline[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
disp = new google.maps.DirectionsRenderer(rendererOptions);
disp.setMap(map);
disp.setDirections(response);
//Markers
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation[routeNum].latlng = legs[i].start_location;
startLocation[routeNum].address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation[routeNum].latlng = legs[i].end_location;
endLocation[routeNum].address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline[routeNum].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
}
}
polyline[routeNum].setMap(map);
//map.fitBounds(bounds);
startAnimation(routeNum);
} // else alert("Directions request failed: "+status);
}
}
var lastVertex = 1;
var stepnum=0;
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol= [];
//----------------------------------------------------------------------
function updatePoly(i,d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2[i].getPath().getLength() > 20) {
poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
if (poly2[i].getPath().getLength()>1) {
poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
}
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
} else {
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
}
}
//----------------------------------------------------------------------------
function animate(index,d) {
if (d>eol[index]) {
marker[index].setPosition(endLocation[index].latlng);
return;
}
var p = polyline[index].GetPointAtDistance(d);
//map.panTo(p);
marker[index].setPosition(p);
updatePoly(index,d);
timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}
//-------------------------------------------------------------------------
function startAnimation(index) {
if (timerHandle[index]) clearTimeout(timerHandle[index]);
eol[index]=polyline[index].Distance();
map.setCenter(polyline[index].getPath().getAt(0));
poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});
timerHandle[index] = setTimeout("animate("+index+",50)",2000); // Allow time for the initial map display
}
//----------------------------------------------------------------------------
</script>
</head>
<body onload="initialize()">
<div id="tools">
<button onclick="setRoutes();">Start</button>
</div>
<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
<style>
html
{
height:100%;
}
body
{
height:100%;
margin:0px;
font-family: Helvetica,Arial;
}
</style>
<script type="text/javascript">
var map;
var geocoder;
var marker;
var people = new Array();
var people2 = new Array();
var latlng;
var infowindow;
var lats=6.9271;
var markersz = new google.maps.Marker;
var markers2 = new google.maps.Marker;
$(document).ready(function() {
var mapOptions = {
center: new google.maps.LatLng(7.8731, 80.7718), // Coimbatore = (11.0168445, 76.9558321)
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
ViewCustInGoogleMap();
});
window.setInterval(function(){
ViewCustInGoogleMap();
}, 5000);
function ViewCustInGoogleMap() {
//deleting the previous set mark on the map
markersz.setMap(null);
markers2.setMap(null);
lats = lats+0.01;
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "DULA TEST<br/><h1>HHH</h1><a href=https://www.google.lk?st=kk target=_blank>CLICK</a>", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "'+lats+',79.8612", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
markersz = setMarker(people[i]);
}
//-----------------------------------------------------------------------------------------------------------------
//getting lats and longs from the controller
$.ajax({
type: 'post',
url: 'http://localhost/GPS/Login/latsAndLongs',
data: "",
dataType: 'json',
success: function(response) {
people2 = JSON.parse(response);
for (var i = 0; i < people2.length; i++) {
//setting the current mark and returning the mark object so that it can be deleted in the next iteration
markers2=setMarker2(people2[i]);
}
}
});
//var data2 = '[{ "DisplayText": "DULA TEST2", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "6.5854,79.9607", "MarkerId": "Seller"}]';
}
//---------------------------------------------------------------------
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
//alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
marker = new google.maps.Marker;
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "http://www.myiconfinder.com/uploads/iconsets/256-256-a5485b563efc4511e0cd8bd04ad0fe9e.png" // Give ur own image
});
//marker.setMap(null);
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
return marker;
}
}
//-----------------------------
function setMarker2(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
return marker;
}
</script>
Move a list of marker and zoom particular marker while iterating.
1. Get Imei_no.
2. Push imei_no in variable.
3. Create Map.
4. Get details based on imei_no.
5. Create Maker.
6. Push maker in test.
7. Delete marker.
8. Return to autoUpdate.
Live Tracking Done by Sureshchan...
if (true) {
var listimei = [];
$scope.listimei = [];
$http.get('school/transport/scroute/viewIMEI?imeiNo=' + routeid).success(function(response) {
//1.
console.log(response);
if (response.viewRoute == 0) {
logger.logError("IMEI No. not available");
$state.go("app.school.scTransport.scVehicleTracking.list");
} else {
//brown
$scope.brown = response.viewRoute[0].emptveh;
//2.
for (var b = 0; b < response.viewRoute.length; b++) {
listimei.push(response.viewRoute[b].imeiNo);
}
//3.
var mapOptions = {
center: new google.maps.LatLng(13.0037, 80.1476),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('viewallmap'), mapOptions);
var infoWindow = new google.maps.InfoWindow;
var test = [];
var marker;
function autoUpdate() {
if (marker == null){
$scope.locData = [];
var y = 0;
var g = 0;
var r = 0;
var n = 0;
$http.get('school/transport/scroute/getListImei?imeiNo=' + listimei).success(function(response) {
//4.
console.log(response);
$scope.assetloader = true;
for(var l = 0;l<response.viewImeiList.length;l++){
//time
var startTime = new Date();
var endTime = new Date(response.viewImeiList[l].lastmove);
var difference = startTime.getTime() - endTime.getTime();
var resultInMinutes = difference / 60000;
var result = Math.round(resultInMinutes);
//for date
var dateObj = new Date(response.viewImeiList[l].lastmove);
var month1 = ("0" + (dateObj.getUTCMonth() + 1)).slice(-2);//months from 1-12
var day1 = ("0" + dateObj.getUTCDate()).slice(-2);
var year1 = dateObj.getUTCFullYear();
var testdate = year1 + "-" + month1 + "-" + day1;
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
if (response.viewImeiList[l].nosignal == 1) {
$scope.black = n + 1;
n++;
}else if(testdate != today){
$scope.black = n + 1;
n++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "000000","FFFFFF");
$scope.locData.push($scope.view);
}
else if (response.viewImeiList[l].speed == 0) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed != 0 && result > 15) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed > 50 && result < 15) {
$scope.red = r + 1;
r++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "FF0000","000000");
$scope.locData.push($scope.view);
} else {
$scope.green = g + 1;
g++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "00ff00","000000");
$scope.locData.push($scope.view);
}
}
var locations = $scope.locData;
for (var i = 0; i < locations.length; i++) {
var city = locations[i][0];
var state = locations[i][1];
var lat = locations[i][2];
var lng = locations[i][3];
var desc = locations[i][4];
var textcol = locations[i][5];
var z = i;
var myLatLng = new google.maps.LatLng(lat, lng);
var content = '<div class="map-content"><h3>' + state +
'</h3></div>';
//5.
marker = new google.maps.Marker({
map: map,
title: state,
position: myLatLng,
icon : 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + city + '|' + desc + '|' +textcol,
draggable : true,
zIndex: z
});
//6.
test.push(marker);
//mouseover
google.maps.event.addListener(marker, 'click', (function(marker, content) {
return function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, content));
// add the double-click event listener
google.maps.event.addListener(marker, 'dblclick', function(event){
map = marker.getMap();
map.setCenter(overlay.getPosition()); // set map center to marker position
smoothZoom(map, 12, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
})
// the smooth zoom function
function smoothZoom (map, max, cnt) {
if (cnt >= max) {
return;
}
else {
y = google.maps.event.addListener(map, 'zoom_changed', function(event){
google.maps.event.removeListener(y);
self.smoothZoom(map, max, cnt + 1);
});
setTimeout(function(){map.setZoom(cnt)}, 80);
}
}
}
});
myVar = setTimeout(autoUpdate, 40000);
}
if(test.length !=0){
//7.
for (var k = 0; k < test.length; k++) {
if (test[k].getMap() != null) {
test[k].setMap(null);
}
}
test1();
}
}
function test1(){
//8.
test = [];
marker = null;
autoUpdate();
}
autoUpdate();
}
});
}

Prevent Adding everytime i change the Drop Down Value

I'm Stuck in a situation where the Marker on every Change on Dropdown List of radius is Adding Marker everytime. . .Do I need to SetMap Null every Change of Dropdown list so the Marker Doesn't become populated with Identical Marker??
Or other approach or Changes that i need to do in my Set of Codes
var Rad = 0;
var customerlocationID = 0;
var geocoder, infoBubble, geocode;
var map;
var selectedMarker;
var ID;
//var mgr;
$("#ddlRadius").live("change", function () {
var selectValue = "";
selectValue = $("#ddlRadius option:selected").val();
if (selectValue == "77") {
Rad = 5;
codeAddress(customerlocationID, Rad);
}
else if (selectValue == "78") {
Rad = 10;
codeAddress(customerlocationID, Rad);
}
else if (selectValue == "79") {
Rad = 25;
codeAddress(customerlocationID, Rad);
}
else if (selectValue == "80") {
Rad = 50;
codeAddress(customerlocationID, Rad);
}
else if (selectValue == "81") {
Rad = 100;
codeAddress(customerlocationID, Rad);
}
});
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
geocode = new google.maps.Geocoder();
// Used to Set the Center of the Maps on the Logged User
$.getJSON('/Dashboard/LoadAddress', function Geocoding(address) {
$.each(address, function () {
customerlocationID = this["ID"];
var currValAddress = this["AddressLine1"];
var Latitude = this["Latitude"];
var Longitude = this["Longitude"];
var LatLang = new google.maps.LatLng(Latitude, Longitude);
var addresse = {
zoom: 8,
center: LatLang,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), addresse);
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90));
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
});
codeAddress(customerlocationID, Rad);
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress(customerlocationID, Rad) {
infoBubble = new InfoBubble({
map: map,
shadowStyle: 0,
padding: 10,
borderRadius: 10,
arrowSize: 15,
maxWidth: 300,
borderWidth: 1,
borderColor: '#ccc',
arrowPosition: 50,
arrowStyle: 0
});
$.getJSON('/Dashboard/LoadWorkerList1' + '?customerLocationID=' + customerlocationID + '&radius=' + Rad, function Geocode(addresses) {
$.each(addresses, function () {
var currVal = this["AddressLine1"];
var Name = this["Name"];
var Gender = this["Gender"];
var Bdate = this["Birthdate"];
ID = this["Worker_ID"];
var distance = this["Distance"];
var workerDetailIDDD = this["Worker_ID"];
var Latitude = this["Latitude"];
var Longitude = this["Longitude"];
var LatLang = new google.maps.LatLng(Latitude, Longitude);
var marker = new google.maps.Marker({
map: map,
icon: '/Content/images/male.png',
position: LatLang,
title: currVal
})
var link = $('' + currVal + '').data('location', LatLang);
$('#places').append($('<li id=\'List\' class=\'List\'>').append(link));
link.on('click', function (event) {
event.preventDefault();
google.maps.event.trigger(addresses[0], "click");
if (selectedMarker) {
selectedMarker.setIcon('/Content/images/male.png');
}
marker.setIcon('/Content/images/maleclicked.png');
selectedMarker = marker;
infoBubble.removeTab(0);
infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br> Distance: " + distance + "<br><br>" + '<center><span style="font-size: 12px !important">View Profile</span></center>');
infoBubble.open(map, marker);
});
google.maps.event.addListener(map, 'idle', function () {
$('#places li').each(function () {
var inside = (map.getBounds().contains($(this).find('a').data('location'))) ? '' : 'none';
$(this).css('display', inside);
});
});
// Listen for user click on map to close any open info bubbles
google.maps.event.addListener(map, "click", function () {
infoBubble.close();
marker.setIcon('/Content/images/male.png');
});
google.maps.event.addListener(map, "dragstart", function () {
infoBubble.close();
marker.setIcon('/Content/images/male.png');
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
if (selectedMarker) {
selectedMarker.setIcon('/Content/images/male.png');
}
marker.setIcon('/Content/images/maleclicked.png');
selectedMarker = marker;
infoBubble.removeTab(0);
infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br> Distance: " + distance + "<br><br>" + '<center><span style="font-size: 12px !important">View Profile</span></center>');
infoBubble.open(map, marker);
}
})(marker, currVal));
addresses.push(marker);
})
google.maps.event.trigger(map, 'bounds_changed');
})
}
window.onload = function () {
initialize();
}

Infinite Looping on Controller and on Cshtml

I'm Currently working on Google Maps API but it is new to me so ive read some pages and start working until i encountered this kind of Bug/Glitch where the Value Keeps on Looping until the page Crash. .
Can Someone Help me or Point me where is the Problem on my Codes:
I don't have Errors
This is the Code in my Cshtml:
<script type="text/javascript">
var geocoder, infoBubble;
var map;
//var mgr;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
codeAddress();
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
infoBubble = new InfoBubble({
map: map,
shadowStyle: 0,
padding: 10,
borderRadius: 10,
arrowSize: 15,
maxWidth: 300,
borderWidth: 1,
borderColor: '#ccc',
arrowPosition: 50,
arrowStyle: 0
});
$.getJSON('/Dashboard/LoadWorkerList', function (address) {
$.each(address, function () {
var currVal = this["AddressLine1"];
var Name = this["Name"];
var Gender = this["Gender"];
var Bdate = this["Birthdate"];
var ID = this["Worker_ID"];
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
var link = $(''+currVal+'')
.data('location', results[0].geometry.location);
$('#places').append($('<li>').append(link));
link.on('click', function (event) {
event.preventDefault();
google.maps.event.trigger(address[0], "click");
infoBubble.removeTab(0);
infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br><br>" + '<center>View Profile</center>');
infoBubble.open(map, marker);
}
);
google.maps.event.addListener(map, 'idle', function () {
$('#places li a').css('display', function () {
return (map.getBounds().contains($(this).data('location')))
? ''
: 'none';
});
});
</script>
And this is the Code in my Controller:
public JsonResult LoadWorkerList()
{
var workerList = new List<Worker_Address>();
// check if search string has value
// retrieve list of workers filtered by search criteria
var list = (from a in db.Worker_Address
join b in db.Workers
on a.WorkerID equals b.ID
where a.LogicalDelete == false
&& b.LogicalDelete == false
select new
{
b.ID,
b.LastName,
b.FirstName,
b.MiddleName,
b.Gender_LookID,
b.BirthDate,
a.WorkerID,
a.Address_Line1,
a.Address_Line2,
a.City,
a.State_LookID,
a.ZipCode,
a.LogicalDelete,
}).ToList();
List<WorkerAddressInfo> wlist = new List<WorkerAddressInfo>();
foreach (var row in list)
{
WorkerAddressInfo ci = new WorkerAddressInfo
{
ID = row.ID,
Worker_ID = row.WorkerID,
AddressLine1 =
row.Address_Line1 + " " + row.Address_Line2 + " " + row.City + " " +
GetLookupDisplayValById(row.State_LookID),
Name = row.FirstName + " " + row.MiddleName + " " + row.LastName,
Birthdate = row.BirthDate.ToString("MM/dd/yy"),
Gender = GetLookupDisplayValById(row.Gender_LookID),
LogicalDelete = row.LogicalDelete
};
wlist.Add(ci);
}
return Json(wlist.ToList().OrderBy(p => p.AddressLine1), JsonRequestBehavior.AllowGet);
}

Making the Looped Data from GetJson Array a Link

I have a problem, im making a list for the markers on my Google Maps but i want it to make a link that will display the Values of that on the List, it is looped by getJson and the <li> is only appended upon loop.
Can someone help me making it a Link that will alert the values?
This is my sets of codes:
<script type="text/javascript">
var geocoder;
var map;
//var mgr;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
codeAddress();
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJSON('/Dashboard/LoadWorkerList', function (address) {
$.each(address, function () {
var currVal = this["AddressLine1"];
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
$('#places').append($('<li/>')
.text(currVal)
.data('location', results[0].geometry.location));
google.maps.event.addListener(map, 'bounds_changed', function () {
$('#places li').css('display', function () {
return (map.getBounds().contains($(this).data('location')))
? ''
: 'none';
});
});
//mgr = new MarkerManager(map);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(currVal);
infowindow.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
google.maps.event.trigger(map, 'bounds_changed');
});
}
window.onload = function () {
initialize();
}
</script>
LoadWorkerList:
public JsonResult LoadWorkerList()
{
var workerList = new List<Worker_Address>();
// check if search string has value
// retrieve list of workers filtered by search criteria
var list = (from a in db.Worker_Address
where a.LogicalDelete == false
select a).ToList();
List<WorkerAddressInfo> wlist = new List<WorkerAddressInfo>();
foreach (var row in list)
{
WorkerAddressInfo ci = new WorkerAddressInfo
{
ID = row.ID,
Worker_ID = row.WorkerID,
AddressLine1 = row.Address_Line1 + " " + row.Address_Line2+ " " +row.City + " "+ GetLookupDisplayValById(row.State_LookID),
LogicalDelete = row.LogicalDelete
};
wlist.Add(ci);
}
return Json(wlist.ToList().OrderBy(p => p.AddressLine1), JsonRequestBehavior.AllowGet);
}
The following line:
$('#places').append($('<li/>')
should be changed. / in front of > should be removed:
$('#places').append($('<li>')
If the list with ID places is available you will get the list of addresses.

undefined not found ie7

IE7 is giving me an issue with a script, using Google Maps API.
When the page is loaded, it says in a alert box 'undefined not found'.
This only happens in IE7, not IE8, nor IE9. Fine in other browsers too, i guess there is a coding error. As soon as i take out JS, no warning but map doesn't work, obviously.
Here is my entire JS. Thanks in advance!
var map;
var markers = [];
var infoWindow;
var panorama;
function init_map() {
map = new google.maps.Map(document.getElementById("map"), {
//center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
infoWindow = new google.maps.InfoWindow();
var address = $('#address').val();
var address_optional = $('#address_optional').val();
if (address == '' && address_optional != '1') init_location();
else searchLocations(address_optional);
}
function init_location(lat, lng, zoom) {
if (lat === undefined) lat = 40;
if (lng === undefined) lng = -100;
if (zoom === undefined) zoom = 4;
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
}
$("#next").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number + 1));
searchLocations();
});
$("#previous").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number - 1));
searchLocations();
});
function searchLocations() {
var address = $('#address').val();
var geocoder = new google.maps.Geocoder();
var address_optional = $('#address_optional').val();
geocoder.geocode({
address: address
}, function(results, status) {
if ((status == google.maps.GeocoderStatus.OK)) {
searchLocationsNear(results[0].geometry.location);
} else {
if (address_optional == '1') {
searchLocationsNear('', 1);
} else {
alert(address + ' not found');
}
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
}
function createSidebarEntry(markerNum, sidebarContent, markerContent, lat, lng) {
var div = document.createElement('div');
div.innerHTML = sidebarContent;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
div.onclick = function() {
infoWindow.setContent(markerContent);
infoWindow.open(map, markers[markerNum]);
init_location(lat, lng, 16);
var latlng = new google.maps.LatLng(
parseFloat(lat), parseFloat(lng));
createMarker(latlng, lat, lng, markerContent);
}
return div;
}
function resizeMap(width, height) {
$('#map').animate({
width: width,
height: height
}, function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.getCenter());
});
}
function streetView(lat, lng) {
var dom = 'streetview';
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom));
displayStreetView(lat, lng, dom);
if ($('#map').height() == 600) {
resizeMap(850, 300);
$('#streetview').height(300);
}
}
function searchLocationsNear(center, address_optional) {
clearLocations();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
var page_number = $('body').data("page_number");
if (page_number == null) {
page_number = 1;
$('body').data("page_number", page_number);
}
var categoryid = $('#categoryid').val();
if (address_optional == '1') var searchUrl = 'map_data.php?categoryid=' + categoryid + '&page_number=' + page_number + '&address_optional=' + address_optional;
else var searchUrl = 'map_data.php?lat=' + center.lat() + '&lng=' + center.lng() + '&categoryid=' + categoryid + '&page_number=' + page_number;
//alert(searchUrl);
$.ajax({
type: 'GET',
url: searchUrl,
dataType: 'json',
success: function(msg) {
var locations = msg.locations;
var markersContent = msg.markersContent;
var sidebarContent = msg.sidebarContent;
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var name = locations[i]['name'];
var address = locations[i]['address'];
var distance = parseFloat(locations[i]['distance']);
var latlng = new google.maps.LatLng(
parseFloat(locations[i]['lat']), parseFloat(locations[i]['lng']));
var sidebarEntry = createSidebarEntry(i, sidebarContent[i], markersContent[i], locations[i]['lat'], locations[i]['lng']);
sidebar.appendChild(sidebarEntry);
createOption(name, distance, i);
createMarker(latlng, locations[i]['lat'], locations[i]['lng'], markersContent[i]);
bounds.extend(latlng);
}
$('#pagination').html(msg.pagination);
map.fitBounds(bounds);
}
});
resizeMap(850, 600);
$('#streetview').html('').height(0);
}
function createMarker(latlng, lat, lng, html) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, this);
});
$("#sidebar div").click(function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
}
function displayStreetView(lat, lng, dom) {
var latlng = new google.maps.LatLng(lat, lng);
var panoramaOptions = {
position: latlng,
pov: {
heading: 270,
pitch: 0,
zoom: 1
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom), panoramaOptions);
map.setStreetView(panorama);
}

Categories

Resources