Update Marker in Google Maps without loading whole map - google-maps

I have an Application in CI where i am getting the current location of a employee after every two seconds from database and draw its current location marker
my code is working but after every 2 seconds it will update the marker by showing a new location marker but keep showing old markers too.
i want to delete old marker of employee before showing the new marker.
here is my code
<script>
function initMap4(data,id) {
var map2 = new google.maps.Map(document.getElementById('map2'), {
zoom: 8,
center: new google.maps.LatLng(31.1704,72.7097),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
window.setInterval(function(){
$.ajax({
type: 'POST',
url: '<?php echo base_url() ?>salesman/get_salesman_by_id',
data : { id: id},
success: function (response) {
var result = response ;
update(result);
}
});
},2000);
function update(data){
var clicked = false;
var locations2;
if(data){
locations2= JSON.parse(data);
}else{
locations2 = JSON.parse('<?php echo $clocation; ?>');
}
var locations_array2= [];
$.each(locations2[0], function( index, value ) {
locations_array2.push([
value.first_name,
value.lat,
value.long,
value.checkin_time,
value.checkout_time,
]);
});
locations2=locations_array2;
for (i = 0; i < locations2.length; i++)
{
var currTime = Date.now() - 300000;
var online = locations2[i][5];
var MyOnlineMarker = {
position: new google.maps.LatLng(locations2[i][1], locations2[i][2]),
map: map2,
};
if(locations2[i][4] == "" ){
marker = new google.maps.Marker(MyOnlineMarker);
}else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations2[i][1], locations2[i][2]),
map: map2,
icon: 'assets/Images/red.png'
});
}
}
}
}
</script>

Ive solved it
by pushing marker in an array than delete them

Related

Show User location on google maps

First thing is I will tell you I am new to google maps and some of it is very confusing to me. What I need to do is show a users location and have the appropriate markers show up. I have the database all ready and somewhat of the Google map.
What I am working with is an example from here. What I can either get is the markers if I use a static LatLng or just the users dynamic location with no markers.
Need help please. And if you downvote this post please let me know why.
Code I am using can be found at https://jsfiddle.net/8q1apmdy/9/ and show where in the blow code is where I am missing something, most likely small or in the wrong position.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
var map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
}
a) While running your code locally, I was getting 'pos' undefined, so I moved the following code 'var map = new google.maps.Map(..' inside the getCurrentPosition(){...
b) Then I got another error ' InvalidValueError: setMap: not an instance of Map;' so created a 'var map' globally.
Loaded the map successfully, but still markers were not loaded. while debugging your code at this point 'var marker = new google.maps.Marker({...' it is iterating for all markers from xml but somehow markers are not adding to the map..dont know the reason yet?
So I have tried in a different way. Please see all markers from xml displayed on map. Here I am just getting the 'name' in marker, you might need to add other parameters like id, address etc.
JSFiddle added for reference
var infowindow;
var map;
//var downloadUrl;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-33.868820, 151.209290),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
downloadUrl("https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute('id');
var address = markers[i].getAttribute('address');
var type = markers[i].getAttribute('type');
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(latlng);
var marker = createMarker(id, markers[i].getAttribute("name"), address, latlng, type);
}//finish loop
//map.fitBounds(bounds);
}); //end downloadurl
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
function createMarker(id, name, address, latlng, type) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
JSFiddle

Issue to set map in center so multiple marker display

i am using ionic framework. i created map and multiple markers and value came from server side.all data came properly but i don't know why i getting this error-
ionic.bundle.js:25642 TypeError: Cannot read property 'fitBounds' of null
at autoCenter (app.js:147)
at app.js:135
at processQueue (ionic.bundle.js:27879)
at ionic.bundle.js:27895
at Scope.$eval (ionic.bundle.js:29158)
at Scope.$digest (ionic.bundle.js:28969)
at Scope.$apply (ionic.bundle.js:29263)
at done (ionic.bundle.js:23676)
at completeRequest (ionic.bundle.js:23848)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:23789)
code :
angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function ($http) {
var markers = [];
return {
getMarkers: function () {
return $http.get("http://localhost:8080/LocationServices/markers.php").then(function (response) {
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function ($cordovaGeolocation, Markers) {
var apiKey = false;
var map = null;
var zoomVal = 15
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true };
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Latitude current: ", position.coords.latitude);
console.log("Longitude current: ", position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function () {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: latLng
});
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}, function (error) {
console.log("Could not get location");
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}
function loadMarkers(map) {
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function (markers) {
console.log("Markers: ", markers);
var markersss = new Array();
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
console.log("Latitude: ", record.lat);
console.log("Longitude: ", record.lng);
var markerPos = new google.maps.LatLng(record.lat, record.lng);
console.log("marker position", "" + markerPos);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
markersss.push(marker);
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
autoCenter(map, markersss);
});
}
function autoCenter(map1, markersss) {
//Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
//Go through each...
for (var i = 0; i < markersss.length; i++) {
bounds.extend(markersss[i].position);
console.log("bounds position", "" + markersss[i].position);
}
//Fit these bounds to the map
map1.fitBounds(bounds);
map1.setCenter(bounds.getCenter());
//remove one zoom level to ensure no marker is on the edge.
map1.setZoom(vm.googleMap.getZoom() - 1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if (map1.getZoom() > zoomVal) {
map1.setZoom(zoomVal);
}
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function () {
initMap();
}
}
})
.controller('MapCtrl', function ($scope, $state, $cordovaGeolocation) {
});
The map will only be created when $cordovaGeolocation.getCurrentPosition was successfull, but you also call loadMarkers when it wasn't successfull(map is null in this case)
Solution: create the map outside of the getCurrentPosition-callbacks (with a default-value for center).
In the success-callback create the marker and set the center of the map
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true },
mapOptions = {
center: new google.maps.LatLng(-37.92,151.25),
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function () {
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var center = new google.maps.LatLng( position.coords.latitude,
position.coords.longitude);
map.setCenter(center);
new google.maps.Marker({
map : map,
animation : google.maps.Animation.DROP,
position : center
});
loadMarkers(map);
}, function (error) {
loadMarkers(map);
});
});
}

retrieving latitude and longitude from database(db2) and show in map in IBM worklight

I have saved latitude and longitude in database(db2).I want to use them to show their location in map.I am working with IBM Worklight and as database I am using DB2.
My problem is I can retrieve value from database,store it in a variable but could not be able to pass the value in the function of map where it can be used as latitude and longitude.
Any positive help would be appreciated.Thanks in advance.
My approach:
CODE:
var mylat;
var mylon;
var clat;
var clon;
function maplo() {
//database value,I have stored them in a text input type
clat=$("#lati").val();
clon=$("#long").val();
}
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
mylat=position.coords.latitude;
mylon=position.coords.longitude;
}
function success(position) {
//reload();
maplo();
showPosition(position);
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('article').appendChild(mapcanvas);
var flat=clat;
var flon=clon;
alert("custom latitude is : "+flat);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coords1 = new google.maps.LatLng(flat, flon);
var options = {
zoom: 16,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
var geolocation = new google.maps.Marker({
position: coords1,
map: map,
title: 'Your car location',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function searchcarl()
{
var a=$("#searchcar").val();
var invocationData={
adapter:'park',
procedure :'procedure4',
parameters:[a]
};
var options={
onSuccess:success6,
onFailure:fail6
};
WL.Client.invokeProcedure(invocationData, options);
}
function success6(result){
if((result.invocationResult.resultSet.length)>0)
{
alert("location fetching!");
var I=result.invocationResult.resultSet[0].LAT;
var J=result.invocationResult.resultSet[0].LON;
$("#lati").val(I);
$("#long").val(J);
}
else{
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function fail6()
{
alert("fail6");
}
I will update the code as follows:
// create a map global variable
var map;
function initMap(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('body').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom : 16,
center : coords,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position : coords,
map : map,
title : "You are here!"
});
}
// adds a marker to the map
function addCarLocationMarker(lat, lng) {
var coords = new google.maps.LatLng(lat, lng);
var geolocation = new google.maps.Marker({
position : cords,
map : map,
title : 'Your car location',
icon : 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// once you know the user location, init the map
initMap(position);
});
} else {
alert('Geo Location is not supported');
}
function searchcarl() {
var a = $("#searchcar").val();
var invocationData = {
adapter : 'park',
procedure : 'procedure4',
parameters : [ a ]
};
var options = {
onSuccess : adapterSuccess,
onFailure : adapterFailed
};
WL.Client.invokeProcedure(invocationData, options);
}
function adapterSuccess(result) {
if ((result.invocationResult.resultSet.length) > 0) {
alert("location fetching!");
var I = result.invocationResult.resultSet[0].LAT;
var J = result.invocationResult.resultSet[0].LON;
// add the marker directly to the map
addCarLocationMarker(I, J);
}
else {
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function adapterFailed() {
alert("adapter invocation failed");
}
Like Idan mentioned, it's not a good idea to store the coordinates in text boxes to then use the text boxes as the source of the coordinates.
You should add the marker directly after you received the coordinates from the adapter. In this case I created a separate function initMap to initialize the map and center it on the current user's location. It is a good idea to make your functions smaller to perform one single task.
I removed some function that I thought you didn't need or were duplicating functionality namely maplo, getLocation and showPosition.

Can someone tell me why I can see an InfoWindow when I click on an map marker?

Here is my code that will pull data from mysql and display the markers on the map. But I cant get the info windows to show when I click on a marker. Thank for any help.
The reference to the infowindows is at the very bottom on the page close to the end of the code after the ajax reference.
Thanks
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function LoadMarkers(encodedString)
{
var bounds = new google.maps.LatLngBounds();
var stringArray = [];
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
info.open(map,this);
infos[0]=info;
});
bounds.extend(lat);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
map.fitBounds(bounds);
}
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = null;//new google.maps.Map(document.getElementById("map_canvas"), myOptions);
jQuery(document).ready( function($){
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
LoadMarkers(document.getElementById("encodedString").value);
setInterval(function () {
jQuery.ajax({
url:'ajaxload.php',
type: "POST",
data: {'refreshed':true},
success: function(data)
{
LoadMarkers(data);
}
});
}, 10000);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
The function LoadMarkers is defined in global scope, but the function closeInfos is defined locally inside the $.ready-callback.
Because of that the call of closeInfos() inside the click-handler of the marker fails and stops the further execution of the click-handler.
You must make closeInfos global accessible:
window.closeInfos=function(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}

Reset bounds on Google Maps API v3

How can I reset the bounds of a GoogleMap when user selects an option? Bounds have already been set to include a 'big picture' of the area, I want to zoom to a specfic area when the user selects an option...and need to do so by resetting the bounds. Extending to include the lat/longs won't work, as they are already included.
You have to create a new bounds object, add the map points to it, and then add the bounds object to the map.
Condensed solution:
//Create new bounds object
var bounds = new google.maps.LatLngBounds();
//Loop through an array of points, add them to bounds
for (var i = 0; i < data.length; i++) {
var geoCode = new google.maps.LatLng(data[i][1], data[i][2]);
bounds.extend(geoCode);
}
//Add new bounds object to map
map.fitBounds(bounds);
My complete solution for removing existing markers, getting an updated array of points via ajax, adding them to the map, and then resetting the map boundries.
<script type="text/javascript">
var map;
var markers = [];
$(document).ready(function () {
initialize();
setInterval(function () {
setMarkers();
}, 3000);
});
google.maps.visualRefresh = true;
function initialize()
{
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(45, -93),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers();
}
function setMarkers()
{
removeMarkers();
var bounds = new google.maps.LatLngBounds();
$.ajax({
url: "/Your/Url?variable=123",
dataType: "json",
success: function (data) {
//Data returned is made up of string[3]
if (data != null) {
//loop through data
for (var i = 0; i < data.length; i++) {
var geoCode = new google.maps.LatLng(data[i][1], data[i][2]);
var marker = new google.maps.Marker({
position: geoCode,
map: map,
title: data[i][0],
content: '<div style="height:50px;width:200px;">' + data[i][0] + '</div>'
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
markers.push(marker);
bounds.extend(geoCode);
}
}
map.fitBounds(bounds);
}
});
}
function removeMarkers()
{
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}