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();
}
Related
i have an phone gap application , and i was working with sub function in other project in phonegap that has java script index file , now i want to integrate the sub index file to my original project , and i know i cant have two indexes file because phonegap app has onsucees , and deviceReady function
i want to convert this code to a regular java script file
$("#tourButton").click(function(){
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
// app.receivedEvent('deviceready');
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onError);
},
onSuccess: function(position){
//My coordinates: Latitude: 21.371479, Longitude: 39.794234
//var longitude = position.coords.longitude;
//var latitude = position.coords.latitude;
var longitude = 39.794234;
var latitude = 21.371479;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title: 'my location'
});
//document.getElementById("jjj").innerHTML=longitude + ", " + latitude;
var hours = $("input:text").val();
var radioValue = $("input[name='transport']:checked").val();
var distanceInKM;
var serviceURL ;
var dataArray = [];
var query ;
var matches = hours.match(/^\d{1,2}(?:\.\d{1,2})?$|^\.\d{1,2}$/);
if (hours!="" && !matches){
alert( " القيمة " + hours + " غير صحيحة .. الرجال ادخال قيمة اخرى (مثال 4 أو 4.5) " );
}
else if (!hours.match(/\S/)) {
alert(" الرجاء تحديد ساعات الفراغ ");
}
else if ($("input[type=radio]:checked").length <= 0) {
alert("الرجاء اختيار وسيلة المواصلات المفضلة");
}
else if (hours>0 && radioValue == "DRIVING") { //DRIVING is selected
distanceInKM = drivingDistanceCal(hours);
//document.getElementById("mmm").innerHTML = drivingDistanceCal(hours);
serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
query = { user: distanceInKM, lat: latitude, lng: longitude };
}
else if (hours>0 && radioValue == "WALKING") { //WALKING is selected
distanceInKM = walkingCalDistanceCal(hours);
//document.getElementById("mmm").innerHTML = walkingCalDistanceCal(hours);
serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
query = { user: distanceInKM, lat: latitude, lng: longitude };
}
else{
alert(" الرجاء تحديد ساعات الفراغ بالإضافة إلى وسيلة المواصلات ");
}
function drivingDistanceCal(hours){
distanceInKM = (45 * hours)/3;
return distanceInKM;
//alert(distanceInKM);
}
function walkingCalDistanceCal(hours){
distanceInKM = (4.82803 * hours)/3;
return distanceInKM;
//alert(distanceInKM);
}
$.getJSON( serviceURL,query)
.done(function( data ) {
if(data.items == "no data"){
alert("عذراً لا توجد نتائج");
}
else{
$.each( data.items, function( i, item ) {
dataArray.push([item.L_ID , item.Lat , item.Lon , item.Description ,item.Image , item.Title, item.Type_ID, ]);
});
//document.getElementById("mmm").innerHTML = dataArray.length;
//document.getElementById("result1").innerHTML = dataArray[1][1] + ", " + dataArray[1][2];
document.getElementById("back").style.display = 'block';
var button;
var content = document.getElementById("content");
for(var i = 0 ; i < dataArray.length; i++){
var table = document.getElementById("table");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = dataArray[i][5];
//cell2.innerHTML = dataArray[i][0];
var btn = document.createElement("BUTTON");
var t = document.createTextNode("اختر");
btn.appendChild(t);
btn.setAttribute("id",dataArray[i][0]);
cell2.appendChild(btn);
var tempArray = dataArray[i];
btn.onclick = (function(tempArray) {
return function() {
corefunction(tempArray);
};
}(dataArray[i]));
}
function corefunction(tempArray){
//alert(tempArray[5]);
document.getElementById("back").style.display = 'none';
var distLat;
var distLng;
// start the countdown functionality
// calculating the time in seconds
var twentyFourHours = hours * 60 * 60;
//var twentyFourHours = 1 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
var begin;
// dislay the timer
function Timer(duration, display){
var timer = duration, hours, minutes, seconds;
begin = setInterval(function () {
hours = parseInt((timer /3600)%24, 10)
minutes = parseInt((timer / 60)%60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(hours +":"+minutes + ":" + seconds);
if(timer==600){
alert(" باقي لك١٠ دقايق " );
}
if(timer > 0){
--timer;
}
else if(timer==000){
alert(" انتهت الرحلة وإن شاء الله تكون استفدت ");
window.clearInterval(begin);
}
}, 1000);
var map;
var stop = document.getElementById("stop");
//create buttons for events
var stopbtn = document.createElement("BUTTON");
var t = document.createTextNode("أوقف الرحلة");
stopbtn.appendChild(t);
stopbtn.setAttribute("id","stop");
stop.appendChild(stopbtn);
//display path
distLat = tempArray[1];
distLng = tempArray[2];
var latLong = new google.maps.LatLng(distLat, distLng);
initMap();
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: {lat:latitude,lng:longitude},
destination: latLong,
travelMode: radioValue
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
//autoUpdate();
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
//tracking part
var marker2 = null;
var auto;
function autoUpdate() {
var newLat = position.coords.latitude;
var newLng = position.coords.longitude;
var newlatLong = new google.maps.LatLng(newLat,newLng);
navigator.geolocation.getCurrentPosition(function(position) {
//var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var latLong2 = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if (marker2) {
// Marker already created - Move it
marker2.setPosition(latLong2);
}
else {
// Marker does not exist - Create it
marker2 = new google.maps.Marker({
position:newlatLong,
map: map
});
}
// Center the map on the new position
map.setCenter(latLong2);
});
auto = setTimeout(autoUpdate, 1000);
//Latitude: 21.419833 | Longitude: 39.832421
var distance = haversine(21.419833,39.832421,tempArray[1],tempArray[2]);
//var distance = haversine(newLat,newLng,tempArray[1],tempArray[2]);
function haversine(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
if (distance<=1){
alert("وصلت/اقتربت من وجهتك");
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: latLong,
map: map
});
window.clearInterval(begin);
window.clearTimeout(auto);
stop.removeChild(stopbtn);
}
}
autoUpdate();
//buttons events
$("#stop").click(function(){
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: latLong,
map: map
});
window.clearInterval(begin);
window.clearTimeout(auto);
stop.removeChild(stopbtn);
});
}//end of timer function
}//end of function showRout()
}//end of else
}); //end of getJSON()
}, //end of success state
onError: function(error){
alert("the code is " + error.code + ". \n" + "message: " + error.message);
},//end of error state
};//end of app variable
app.initialize();
}); //end of the whole function
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();
}
});
}
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)
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);
}
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.