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
Related
I am working on a google maps project where I am populating the google maps with markers being read from a database (drawMarkers function). Along with that the google maps finds your current location and keeps refreshing it every couple of seconds to keep track of you on the map. My issue is that have a var closest which is also a function i am using the too find the closest marker then create directions to current locations from there. I did not know how to actually find the closest marker so i borrowed the code from another question from stack overflow and tried to adapt it to this project. I need help to get my closest function to find the closest marker and then to make it the destination in the direction service
$ionicSideMenuDelegate.canDragContent(false);
$scope.getTourMarkers = function () {
tourmarkers.getTourMarkers().success(function (data) {
$scope.tourmarkers = data;
console.log($scope.tourmarkers);
drawMarkers();
});
};
var drawMarkers = function () {
var markers;
var content;
var infoWindow;
for (var i = 0; i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
content: content
});
var point = new google.maps.LatLng($scope.tourmarkers[i].lat, $scope.tourmarkers[i].lon);
markers = new google.maps.Marker({
label: "S",
animation: google.maps.Animation.DROP,
position: point,
map: map,
info: content
});
//SCOPE: 'this' refers to the current 'markers' object, we pass in the info and marker
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
};
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var NAPA_HALL_LAT_LNG = new google.maps.LatLng(38.553801, -121.4212745); // just created this marker for testing purposes
var mapOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'SAC STATE'
});
var dest = new google.maps.Marker({
position: NAPA_HALL_LAT_LNG,
map: map,
title: 'NAPA HALL'
});
///////////////////Directions Display//////////////////////
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//////////////////////////////////////////////////////////////////////////////////////////
//Goal of this function is to find closest marker to current location
//then to create directions to that marker.
//should be refreshed everytime in the onSuccess function
var closest = function (directionsService, directionsDisplay, marker, dest) {
var event;
function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var shortest = -1;
for( i=0;i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
var mlat = $scope.tourmarkers[i].position.lat();
var mlng = $scope.tourmarkers[i].position.lng();
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( shortest == -1 || d < distances[shortest] ) {
shortest = i;
}
}
alert(map.markers[shortest].title);
}
/////**directions feature should have the closest marker be the desitination//
directionsService.route({
origin: marker.position,
destination: dest.position, // i think the marker that should in here is shortest.
travelMode: google.maps.TravelMode.WALKING
}, function(response,status) {
if(status==google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
//////////////////////////////////////////////////////////////////////////////////////////
var onSuccess = function (position) {
marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
directionsDisplay.setMap(map);
dest.setPosition(new google.maps.LatLng(38.553801, -121.4212745));
//dest.setPosition((closest(marker, $scope.tourmarkers)).position); // if you can get this line to work without commenting it out then you're set
closest(directionsService,directionsDisplay, marker,dest);
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
Everything in this project is working properly except that closest function. but even then i have already tested the directionservice and even that is working too. I just need help making the destination in the direction service to be the closest marker to current location.
i think this code is helpful for you i used this code in my project such that your requirement same as my requirement
in the below function 'data' means list of lat lng's from server
function initialize(data) {
size = 0;
counts = 0;
stops = data;
size = stops.length;
if (stops.length > 0) {
var map = new window.google.maps.Map(document
.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer(
{
suppressMarkers : true,
polylineOptions : {
strokeColor : "black"
}
});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map,stops);
/* if (stops.length > 1) */
window.tour.calcRoute(stops,directionsService,
directionsDisplay,size);
}
}
function Tour_startUp(stops) {
var stops=stops;
var counts=0;
if (!window.tour) window.tour = {
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom:10,
center: new window.google.maps.LatLng(17.379818, 78.478542), // default to Hyderabad
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map,stops) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (stops,directionsService, directionsDisplay,size) {
size=size;
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
var tempp=0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
tempp++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].latitude, stops[j].longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
//delay(600);
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
//alert("count test");
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
var totdist=0;
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
var markerletter2= "B".charCodeAt(0)
markerletter += i;
markerletter2 += i;
markerletter = String.fromCharCode(markerletter);
markerletter2 = String.fromCharCode(markerletter2);
createMarker(directionsDisplay.getMap(),legs[i].start_location,legs[i].start_address,markerletter,size);//To display location address on the marker
var routeSegment = i + 1;
var point=+routeSegment+1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += '<b>Point '+ routeSegment +' :</b>'+ ' ' +legs[i].start_address + ' <br> ';
summaryPanel.innerHTML += '<b>Point '+ point +' :</b>'+ ' '+legs[i].end_address + '<br>';
summaryPanel.innerHTML += '<b>Distance Covered '+' :</b>'+legs[i].distance.text + '<br><br>';
var test=legs[i].distance.text.split(' ');
var one=parseFloat(test[0]);
if(test[1]=="m"){
var one=parseFloat(test[0]/1000);
}
totdist=parseFloat(totdist)+parseFloat(one);
}
summaryPanel.innerHTML += '<b> Total Distance :'+totdist + 'km'+ '</b><br><br>';
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,legs[legs.length-1].end_address,markerletter,size);
}
}
});
})(k);
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
}
}//calculate route end
};
}
//to show information on clicking marker
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr,size) {
counts++;
if(counts==size){
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/blue.png";
counts = 0;
}else{
if (iconStr=="undefined") {
iconStr = "red";
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
else{
var markerimageLoc="http://www.google.com/mapfiles/marker"+ iconStr +".png";
// var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
}
icons[iconStr] = new google.maps.MarkerImage(markerimageLoc,
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(25, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, character,size) {
var markerletter = character;
var size=size;
if (/[^a-zA-Z]/.test(character)) {
var markerletter = "undefined";
}
var contentString = '<b>' + label + '</b><br>';
var marker = new google.maps.Marker({
position : latlng,
map : map,
shadow : iconShadow,
icon : getMarkerImage(markerletter,size),
shape : iconShape,
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;
}
Whenever I add an marker and calculate the route on Map Click the second marker it shows two marker on a single icon as shown in the image.
I want only one marker (which is A) in one location
Code Snippet
var map, lat, lng;
var count = 1;
var markers = [],
content_marker;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService;
var pos_source, pos_desti;
// First Function
function onDeviceReady() {
var height = $(window).outerHeight(true);
$("#googleMap").css("height", height);
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
enableHighAccuracy: true
});
}
// GPS Success
function onSuccess(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
/*
* for ( var j = 0; j <= 10; j++) { setInterval(function() { lat++; lng++; },
* 5000);
*/
var mapProp = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// }
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
directionsDisplay.setMap(map);
google.maps.event.addListener(map, 'click', function(event) {
event.latLng;
placeMarker(event.latLng);
});
/*
* Auto Complete Search Box Starts var input =
* (document.getElementById('pac-input')); var input1 =
* (document.getElementById('pac-input1'));
*
* var searchBox = new google.maps.places.SearchBox((input)); var searchBox1 =
* new google.maps.places.SearchBox((input1));
*/
// Auto Complete Search Box Ends }
// Placing Marker
function placeMarker(location) {
if (count == 1 || count == 2) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
google.maps.event.addListener(marker, "click", function() {
marker.setMap(null);
count--;
});
if (count == 1) {
pos_source = location;
content_marker = 'Source';
// marker.setMap(null);
}
if (count == 2) {
// setInterval(function() {
pos_desti = location;
content_marker = 'Destination';
// marker.setMap(null);
calcRoute();
// }, 3000);
}
// google.maps.event.addListener(marker, 'click', function() {
// var x;
// if (confirm("Remove Markers!") == true) {
// x = "You pressed OK!";
// } else {
// x = "You pressed Cancel!";
// }
//
// });
count++;
var infowindow = new google.maps.InfoWindow({
content: content_marker
});
infowindow.open(map, marker);
}
}
// Calculating Distance
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1609.34;
document.getElementById('total').innerHTML = total + ' miles';
}
function deleteMarkers() {
marker.setMap(null);
}
// Calculating route
function calcRoute() {
directionsService = new google.maps.DirectionsService();
alert("Creating Shortest Path !!!");
var request = {
origin: pos_source,
destination: pos_desti,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotalDistance(directionsDisplay.getDirections());
deleteMarkers();
}
});
}
// On GPS Error
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
What's happening is you're getting directions, which renders markers on its start and end points. And you're adding your own marker. You can simply prevent the directions renderer from displaying markers. Add suppressMarkers: true to its options:
var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
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'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);
}
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);
}