Google Map API SetPosition error - google-maps

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);
});

Related

Add new Google Maps marker onClick in existing map

I got an existing map on my page with markers generated by PHP from a database. Works fine. Now I would like to add a new marker in this map.
I can't get it working:
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.2193835,6.5665018),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("geo.php?gmt=<? echo $stringGMT;?>&cat=<? echo $stringAAN;?>&abo=<? echo $stringABO;?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var markersskg=[];
create markers code: working
var icon = customIcons["bar"] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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 addmarker(lat,lon) {
var myLatLng = {lat: lat, lng: lon};
var marker;
//create a marker
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: true
});
}
and the onclick to call:
<div id="map" style="width: 100%; height: 600px"></div>
<button id="button" onClick="addmarker(53.0241066,6.571086);">Drop Markers</button>
You declare var map in load function and then is not visible in addMarker function
try declaring var map in global scope
var map ;
var customIcons = {
skg: {
icon: 'http://mywebsite.nl/img/logo_transparant24.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.2193835,6.5665018),
zoom: 10,
mapTypeId: 'roadmap'
});

How to populate google map markers using JSON?

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

Get latitude and longitude of multiple marker (onclick)

I have multiple markers in my map.
How to create a listener to multiple markers and get their latitude and longitude?
When I tried that event listener at one marker, it works. But when I tried that event listener with my multiple marker, it doesnt work.
Here is my code :
var jakarta = new google.maps.LatLng(-6.211544, 106.845172);
var shelterpoint = [];
var shelterName = [];
<?php while ($row = mysql_fetch_array($result)) { ?>
shelterpoint.push(new google.maps.LatLng(<?=$row['Latitude']?>, <?=$row['Longitude']?>));
shelterName.push("<?=$row['Shelter_Name']?>");
<?php } ?>
var markers = [];
var iterator = 0;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
center: jakarta
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
drop();
google.maps.event.addListener(marker, "click", function (event) {
alert(this.position);
});
}
function drop() {
for (var i = 0; i < shelterpoint.length; i++) {
setTimeout(function() {
addMarker();
}, i * 10);
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: shelterpoint[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title:shelterName[iterator]
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
Please refer the link below.
http://jsfiddle.net/xJ26V/1/
var mapOptions = {
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

How to create Google Maps API Marker with device's geolocation (after its async callback)

Please help. Trying to create a map of Chicago, and have my current known location appear as a marker on that map. The problem is (though I can find no explicit mention of this in any tutorial or doc), it seems I have to declare the marker var in the same scope as (perhaps right after?) I declare the map---global variables don't seem to work. This is difficult, since I'm making an asynchronous call, and thus only have a verified position for my marker in the callback function I've defined. Thus the following code doesn't work...
(function() {
var chicago = new google.maps.LatLng(41.87811, -87.62980);
var info = document.getElementById("info");
var map;
function showError(error)
{
info.innerHTML += "Error: " + error.message;
}
function getLocation(position)
{
current_location = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var marker = new google.maps.Marker({
position: current_location,
map: map
});
}
window.onload = function() {
var mapOptions = {
zoom: 10,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(getLocation, showError);
}
}
})();
I can see no clean way out of this, but would love to be shown otherwise.
If I'm understanding you correctly, than this should work, this is how I handle the asynchronous creation of the marker at the found position in my own app, and it works great! If this isn't what you meant then let me know!
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(lat, lon),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
map = new google.maps.Map(document.getElementById('gmaps'), mapOptions);
locateMe();
}
function locateMe() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
map.setZoom(15);
setMarkerPosition(position.coords.latitude, position.coords.longitude);
updateLocation();
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
}
}
function setMarkerPosition(lati, longi) {
var latLongMarker = new google.maps.LatLng(lati,longi);
marker = new google.maps.Marker({
position: latLongMarker,
map: map,
draggable: false,
title: "Your Location"
});
}

Adding multiple markers in Google Maps V3 using Json

I'm trying to adapt my code with json in google maps. I tried looking at other threads of stackoverflow but did not help me.
How do I show multiple points on the map with the coordinates that are received by json?
This code in firebug shows no errors and the map appears all blue.
var geocoder;
var map;
function initialize() {
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
$.each(data, function(index, c) {
//alert(c.fields['lat']+','+c.fields['lng']); result: -23.0522826,-43.32745712
//Map
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
//options
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
//get the map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//marker
var marker = new google.maps.Marker({
map: map,
position: latlng,
//title: {{i.display.codigo}}
});
//infowindow
var infowindow = new google.maps.InfoWindow({
content: 'oi'
});
//click infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});//close each
});//close getjson
}//close initialize
My response in Json:
[{"pk": 1, "model": "address.coordinates", "fields": {"lat": "-23.0522826", "lng": "-43.32745712"}}, {"pk": 2, "model": "address.coordinates", "fields": {"lat": "-22.24569326", "lng": "-43.7028948"}}]
Thanks!
You have 1 real error here:
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
google.maps.LatLng expects 2 parameters(lat &lng) , but you provide 1(a string containing lat and lng, joined by a comma) . It has to be
latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
But you also have a logical error:
You overwrite the last map created on every each-loop
Create the map and the infoWindow outside of the $.each()
function initialize()
{
var myOptions =
{
zoom: 5,
center: new google.maps.LatLng(1,1) ,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
map= new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds=new google.maps.LatLngBounds();
infowindow = new google.maps.InfoWindow({
content: 'oi'
});
$.each(data, function(index, c) {
var latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+c.pk
});
bounds.extend(latlng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent('pk:'+c.pk);
infowindow.open(map, marker);
});
});//close each
map.fitBounds(bounds);
});//close getjson
}//close initialize