I want to use this WebAPI (JSON)
How can I show a marker using PosX & PosY on google map?
It's simple to achieve, you might not have been tried. Below is the code as per you json.
Javascript:
<script>
//debugger;
var json;
//var json = JSON.parse('[{"PosID":12087,"TagID":11,"Tag":"","AssetID":14,"Asset":"","Driver":"","FixID":0,"Fix":"No Fix","Satellites":0,"PosX":-25.363882,"PosY":131.044922,"PosZ":59.0,"Speed":0.0,"Course":237.0,"HDOP":0.0,"Ignition":0,"Engine":"STOP","Mileage":8.0,"Battery":25.5,"Fuel":0.0,"LocID":0,"Location":"8 Tuas Avenue 18","ZoneID":0,"Zone":"","Remarks":null,"Timestamp":"2015-03-17T12:51:50","RxTime":"2015-03-17T12:51:50","Temperature":0.0,"Temperature2":0.0,"RFID":null,"FuelLevel":0.0,"ActualTemp":0.0,"IsBuffer":false},{"PosID":12088,"TagID":11,"Tag":"","AssetID":14,"Asset":"","Driver":"","FixID":0,"Fix":"No Fix","Satellites":0,"PosX":-25.363882,"PosY":141.044922,"PosZ":59.0,"Speed":0.0,"Course":237.0,"HDOP":0.0,"Ignition":0,"Engine":"STOP","Mileage":8.0,"Battery":25.5,"Fuel":0.0,"LocID":0,"Location":"8 Tuas Avenue 18","ZoneID":0,"Zone":"","Remarks":null,"Timestamp":"2015-03-17T12:51:50","RxTime":"2015-03-17T12:51:50","Temperature":0.0,"Temperature2":0.0,"RFID":null,"FuelLevel":0.0,"ActualTemp":0.0,"IsBuffer":false}]');
$.ajax({
'async': false,
'global': false,
'url': "http://track.asiacom.co.th/fmswebapi/api/posinfo",
'type': "Get",
'dataType': "json",
'success': function (data) {
json = data;
}
});
var m = [];
function initialize() {
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
var myLatlng = new google.maps.LatLng('103.639275', '1.3208363');
var mapOptions = {
center: myLatlng,
zoom: 8
//mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (json.length > 0) {
$(json).each(function (i) {
var latlng = new google.maps.LatLng(json[i].PosX, json[i].PosY);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: json[i].Location
});
m.push(marker);
//extend the bounds to include each marker's position
bounds.extend(marker.position);
});
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
}
}
//google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
initialize();
});
</script>
Html
<div class="map-outer row">
<div id="map-canvas" class="map-view" style="height:700px; width:100%;">hello</div>
</div>
you have to include below js also apart from jquery lib.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
var assets = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://track.asiacom.co.th/fmswebapi/api/posinfo",
'type': "Get",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
alert("OK, data loaded");
});
Something like this code
Related
Hi I'm new to stackoverflow (and coding) but I am working on a web-application where I want to add dynamic markers and infowindows based on an extracted JSON file. There are over 200 markers, so they need to be dynamic. I have code that works to add markers but as soon as I add infoWindows it doesn't. Can anybody see why? The output dropped to just one marker and no infoWindow.
Here is my code:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
I saw a post on stackoverflow with a similar question and tried it that way as well but didnt get any markers.
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
The output of my JSON file looks like this:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
There are a few issues in your code. You should read Using Closures in Event Listeners.
You should set the infowindow content on marker click (not within the loop, as you did)
You should declare the marker variable which is missing
Any variable you are using must be declared, for example for (element in data) should be for (var element in data)
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
console.log(data);
infowindow = new google.maps.InfoWindow();
for (var element in data) {
var marker = new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country;
content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, element));
}
}
});
}
initMap();
#map {
height: 180px;
}
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
I want to show the current position based on user lat & long:
Drop off location always stay static but pick up location (icon) need to move as per lat long, but i am not find the correct way my code is:
$(document).ready(function() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute(pickUpLat,pickUplon,droplat,droplon) {
var pickUpLat = "<?= $pickUpLat ?>";
var pickUplon = "<?= $pickUplon ?>";
var droplat = "<?= $model->drop_off_latitude ?>";
var droplon = "<?= $model->drop_off_longitude ?>";
var start = new google.maps.LatLng(pickUpLat,pickUplon);
var end = new google.maps.LatLng(droplat,droplon);
createMarker(start,"<?= $model->item_delivery_title; ?>","<?= Yii::$app->urlManagerFrontEnd->createAbsoluteUrl('/images/track_route.png')?>");
createMarker(end,"<?= $model->drop_off_address; ?>",'');
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng,title,icon) {
var marker = new google.maps.Marker({
position: latlng,
animation: google.maps.Animation.DROP,
title: title,
icon: icon,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(title);
infowindow.open(map, marker);
});
}
initialize();
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/delivery/map-data'; ?>",
type:"POST",
data:{"delivery_id":<?= $model->id ?>}
})
.done(function(result){
var respon=JSON.parse(result);
if(respon.status==200){
// want to cupdate the pickup location here
}
});
}
setInterval(makeRequest, (3000));
});
Make request function always update the pick up lat and long:
But I am not found any way to move the pick up icon (the van) see image :
The red marker is drop off address and the van is pickup address
You should create two variables for pick up and drop off marker. Also your createMarker function should return marker instance. After you receive request from server update pickUpMarker position.
$(document).ready(function() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
var pickUpMarker, dropToMarker; // add marker variables
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute(pickUpLat,pickUplon,droplat,droplon) {
var pickUpLat = "<?= $pickUpLat ?>";
var pickUplon = "<?= $pickUplon ?>";
var droplat = "<?= $model->drop_off_latitude ?>";
var droplon = "<?= $model->drop_off_longitude ?>";
var start = new google.maps.LatLng(pickUpLat,pickUplon);
var end = new google.maps.LatLng(droplat,droplon);
if(!pickUpMarker) {
pickUpMarker = createMarker(start,"<?= $model->item_delivery_title; ?>","<?= Yii::$app->urlManagerFrontEnd->createAbsoluteUrl('/images/track_route.png')?>");
} else {
pickUpMarker.setPosition(start)
}
if(!dropToMarker) {
dropToMarker = createMarker(end,"<?= $model->drop_off_address; ?>",'');
} else {
dropToMarker.setPosition(start)
}
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng,title,icon) {
var marker = new google.maps.Marker({
position: latlng,
animation: google.maps.Animation.DROP,
title: title,
icon: icon,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(title);
infowindow.open(map, marker);
});
return marker;
}
initialize();
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/delivery/map-data'; ?>",
type:"POST",
data:{"delivery_id":<?= $model->id ?>}
})
.done(function(result){
var respon=JSON.parse(result);
if(respon.status==200){
// want to cupdate the pickup location here
pickUpMarker.setPosition(result.position)
}
});
}
setInterval(makeRequest, (3000));
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to load google map in dialog box on click of a button. Everything is loading except markers. Please help me what is wrong in my code. How to show markers. When i do not use dialog box then its working fine.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image ;
var geocoder;
var latitude;
$(function () {
$("#btnShow").click(function () {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions( { suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
} );
calcRoute();
}
});
});
});
var cList= [];
function showOnMap(){
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for(var i =0;i<cList.length;i++){
var coord = cList[i];
if(coord[0] == "ORG"){
start = coord[1] +", "+coord[2];
alert("start: "+start);
showSteps(coord[1] , coord[2], coord[3]);
}else if(coord[0]== "DEST"){
end = coord[1] +", "+coord[2];
alert("end: "+end);
showSteps(coord[1] , coord[2],coord[3]);
}else if(coord[0]== "WAYPOINT"){
$("#comments").text("WAYPOINT: ");
temp = coord[1] +", "+coord[2];
//alert("way: "+temp);
waypts.push({
location:temp,
stopover:true});
var text = "reached till this stop ";
showSteps(coord[1] , coord[2],text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
//alert("showSteps:"+image+" text"+text);
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if(text == ""){
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
<input id = "btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>
Your map variable is local to the open function for the dialog:
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
Remove the "var" from the beginning of the line that instantiates the google.maps.Map object.
working fiddle
code snippet:
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image;
var geocoder;
var latitude;
$(function() {
$("#btnShow").click(function() {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function() {
$(this).dialog('close');
}
},
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions({
suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
});
calcRoute();
}
});
});
});
var cList = [];
function showOnMap() {
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for (var i = 0; i < cList.length; i++) {
var coord = cList[i];
if (coord[0] == "ORG") {
start = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "DEST") {
end = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "WAYPOINT") {
$("#comments").text("WAYPOINT: ");
temp = coord[1] + ", " + coord[2];
waypts.push({
location: temp,
stopover: true
});
var text = "reached till this stop ";
showSteps(coord[1], coord[2], text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if (text == "") {
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">
<input id="btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>
This is the json data
{
"title": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{title}{/exp:channel:entries}",
"info": "infoz",
"lat": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{sb_lat}{/exp:channel:entries}",
"lng": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{sb_lng}{/exp:channel:entries}"
}
This is the code to get markers:
function setMarkers(center, map) {
var json = (function () {
var json = null;
$.ajax({
'dataType': "json",
'url': "/data/supplier_branches/",
'success': function (data) {
json = data;
console.log(JSON.stringify(data, ["title","info","lat","lng"], 4));
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
latLng = new google.maps.LatLng(data.lat, data.lng);
var data = json[i];
var marker = new google.maps.Marker({
position: latLng,
title: data.info,
map: map
});
infoBranch(map, marker, data);
}
}
My code is returning the json data but not using it as markers. What is the fault?
Entire map code:
function initialize() {
var latitude = -23.92175976307374,
longitude = 24.120724868774414,
center = new google.maps.LatLng(latitude,longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_branches"), mapOptions);
setMarkers(center, map);
function setMarkers(center, map) {
var json = (function () {
var json = null;
$.ajax({
'dataType': "json",
'url': "/data/supplier_branches/",
'success': function (data) {
json = data;
console.log(JSON.stringify(data, ["title","info","lat","lng"], 4));
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
latLng = new google.maps.LatLng(data.lat, data.lng);
var data = json[i];
var marker = new google.maps.Marker({
position: latLng,
title: data.info,
map: map
});
infoBranch(map, marker, data);
}
}
function infoBranch(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.title+data.info);
infoWindow.open(map, marker);
});
// Creating a closure to retain the correct data
// Note how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Console error in Chrome:
Uncaught TypeError: Cannot read property 'length' of null branches_maps.js:30
setMarkers branches_maps.js:30
initialize
$.ajax is asynchronous, so json is undefined when you start that for loop. Stick your for loop inside your $.ajax callback function.
I am using Google Maps API v3. My script works fine and shows a car icon as long as
the marker is undefined. But when I update long lat in the database and the ajax function returns a new long lat via json, marker.setPosition(newLatLng) makes the marker disappear...
Please, help me out, what is the problem? Here is my code:
$(document).ready(function () {
var map;
var marker;
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $c_lat; ?>, <?php echo $c_long; ?>);
var myOptions = {
zoom: 19,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('driver_loc'), myOptions);
}
function getLongLat(){
$.ajax({
type: "POST",
url: "config/getLongLat.php?id=<?php echo $driverId; ?>",
dataType: "json",
success: function(data)
{
var lat=data.lat; //returns new lat via db
var lon=data.lon;
// alert(lat);
var newLatLng = new google.maps.LatLng(lat, lon);
if (marker != undefined)
marker.setPosition(newLatLng);
else
marker = new google.maps.Marker({
position: newLatLng,
map: map,
icon: 'images/car.png',
animation: google.maps.Animation.DROP,
draggable: true
});
}
});
console.log(marker);
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
// google.maps.event.addDomListener(window, 'load', callPosition);
window.setInterval(function(){
getLongLat();
}, 6326);
});
A good practice is to use parseFloat method for json data. A new position can be outside of current view port. To handle it, just use map.setCenter([new_position]) method. You can also change zoom level with map.setZoom([zoom_level]).
In your case:
$(document).ready(function () {
var map;
var marker;
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $c_lat; ?>, <?php echo $c_long; ?>);
var myOptions = {
zoom: 19,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('driver_loc'), myOptions);
}
function getLongLat(){
$.ajax({ type: "POST", url: "config/getLongLat.php?id=<?php echo $driverId; ?>", dataType: "json",
success: function(data){
var lat=parseFloat(data.lat); //returns new lat via db
var lon=parseFloat(data.lon);
var newLatLng = new google.maps.LatLng(lat, lon);
if (marker != undefined){
marker.setPosition(newLatLng);
} else {
marker = new google.maps.Marker({
position: newLatLng,
map: map,
icon: 'images/car.png',
animation: google.maps.Animation.DROP,
draggable: true
});
}
//Center map on a new position
map.setCenter(newLatLng);
//Change zoom level
//map.setZoom(19);
}
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
// google.maps.event.addDomListener(window, 'load', callPosition);
window.setInterval(function(){
getLongLat();
}, 6326);
});