I get my all latitude and longitude values in firebase and display all values in my google map, Its moving also good.
My problem is my car images can not rotate the drivers direction. My self load svg image also.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=myapi"></script>
<script type="text/javascript">
onload = function() {
setInterval(function() {
$.ajax({
type: 'json',
url: 'google-ajax.php',
cache: false,
data: $('#dvMap').serialize(),
dataType: 'json',
success: function(data) {
var markers = data;
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: {
url: "http://localhost/uberx/admin/images/carnew.svg"
}
//icon:"http://localhost/uberx/admin/images/carnew.svg"
});
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
}
});
}, 5000);
}
/*$(document).ready(function(){
onload(); //Call auto_load() function when DOM is Ready
});
//Refresh auto_load() function after 10000 milliseconds
setInterval(onload,10000);*/
</script>
Related
Controler Action code
[HttpGet]
public JsonResult findlatlon()
{
Models.Vehicle_Tracking_SystemEntities entities = new Vehicle_Tracking_SystemEntities();
var latlon = entities.LatLangs.ToList();
return Json(new { AddressResult = latlon }, JsonRequestBehavior.AllowGet);
}
findlatlon.cshtml View code
{ ViewBag.Title = "findlatlon"; }
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCM7G5ruvunb0K7qxm6jb1TssJUwROqs-g" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var myMarkers = [];
$.ajax({
async: false,
type: "POST",
dataType: "json",
url: '#Url.Action("findlatlon", "Home")',
data: '{}',
success: function(result) {
//get address from controller action.....
myMarkers = result.AddressResult;
}
});
//init google map
function googleMap() {
//alert("Hellooooooo");//alert
var mapOptions = {
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//alert(myMarkers[0].Latitude);//alert
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for (i = 0; i < myMarkers.length; i++) {
data = myMarkers[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.Latitude, data.Langitude),
map: map
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.Location_Adress);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
//....
google.maps.event.addDomListener(window, 'load', googleMap);
})
</script>
<div id="map_canvas" style="border-top: none; width: 100%; margin-top: -1px;
height: 250px; background-color: #FAFAFA; margin-top: 0px;">
</div>
Out-Put
{"AddressResult":[{"Id":1,"Latitude":"33.9982","Langitude":"71.4999","Address":"Peshawar","Image":null,"Title":"Peshawar"}]}
So here the AJAX call the controller and controller retrieve the longitude and latitude from the database and return it in json string to view like the above output.
But here I wants that the Latitude and longitude value which return by the json is assign to the
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude)
And I wants to show the location on google map according to the Lat and Long
Here is an example of displaying google map on button clicked, which display accordingly your response, make sure use 'markers.push(v);' need to make change accordingly your code.
var markers = [];
window.onload = function () {
$('#getMap').click(function () {
var deviceId = $('#deviceNumber').val();
if (deviceId != null || deviceId != "") {
$.ajax({
type: "GET",
url: url,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, v) {
markers.push(v);
});
var mapOptions = {
center: new google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var path = new google.maps.MVCArray();
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#4986E7'
});
poly.setPath(path);
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
},
error: function () {
alert('error');
}
});
}
});
}
Hope this helps!
Step-1 First of all Create the Controller Action :
public ActionResult googlemap()
{
return View();
}
Step-2 Create Empty View to this action:
#{
ViewBag.Title = "Google Map";
}
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR-KEY" type="text/javascript"></script>
<script type="text/javascript">
var myMarkers = [];
$.ajax({
async: false,
type: "POST",
dataType: "json",
url: '#Url.Action("googlemapfindlatlon", "Home")',
data: '{}',
success: function (data) {
$.each(data, function (i, v) {
myMarkers.push(v);
});
var mapOptions = {
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//alert(myMarkers[0].Latitude)
//alert(myMarkers[0].Langitude)
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < myMarkers.length; i++) {
var data = myMarkers[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Langitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.Address);
infoWindow.open(map, marker);
});
})(marker, data);
}
//map.setCenter(latlngbounds.getCenter());
//map.fitBounds(latlngbounds);
}
});
//init google map
}
</script>
<div id="map_canvas" style="border-top: none; width: 100%; margin-top: -1px;
height: 250px; background-color: #FAFAFA; margin-top: 0px;">
</div>
Step-3 From the above View the ajax call is made i.e,
url: '#Url.Action("googlemapfindlatlon", "Home")'
so create the "googlemapfindlatlon" JsonResult action in controller:
public JsonResult googlemapfindlatlon()
{
Models.Vehicle_Tracking_SystemEntities entities = new Vehicle_Tracking_SystemEntities();
var latlon = entities.LatLangs.ToList();
//var latlon = entities.LatLangs.OrderByDescending(x => x.Id).Take(1).ToList();
return Json(latlon, JsonRequestBehavior.AllowGet);
}
This is do work correctly for me.
Thank You very much
I am creating an Mobile App where user(customer) will see multiple markers of drivers who is on the 30kms of range from the users current position.
I am able to display multi markers, which are stored in the database by using JSON and JQuery.
function multimarker(map)
{
jQuery.ajax({
url: baseurl + "getdriverlocation.php",
type: "JSON",
async: true,
success: function(data){
var myArray = jQuery.parseJSON(data);// instead of JSON.parse(data)
jQuery(myArray).each(function( index, element ) {
driverlat = element.driver_lat;
driverlng = element.driver_lng;
locations.push([driverlat , driverlng])
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++)
{
var latlng1 = new google.maps.LatLng(locations[i][0], locations[i][1]);
drivermarker=new google.maps.Marker({position:latlng1});
drivermarker.setMap(map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(drivermarker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, drivermarker);
}
})(drivermarker, i));
bounds.extend(latlng1);
}
map.fitBounds(bounds);
}
});
}
also able to plot current position on the same map
function currentpostionmap()
{
if ( navigator.geolocation ) {
function success(pos)
{
var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var image123 = 'https:///developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image123
});
multimarker(map);
}
function fail(error) {
var latlng = new google.maps.LatLng(18.5204, 73.8567);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
marker = new google.maps.Marker({
position: latlng,
map: map
});
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
}
}
Now I just want to display only those marker which are at the distance of 30km from the current position.
Else will not be displayed.
How to do it?
Only add the markers to the map if they meet your criteria. Be sure to include the geometry library.
for (i = 0; i < locations.length; i++) {
var latlng1 = new google.maps.LatLng(locations[i][0], locations[i][1]);
if (google.maps.geometry.spherical.computeDistanceBetween(latlng1,map.getCenter()) < 30000) {
drivermarker=new google.maps.Marker({position:latlng1});
drivermarker.setMap(map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(drivermarker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, drivermarker);
}
})(drivermarker, i));
bounds.extend(latlng1);
}
}
map.fitBounds(bounds);
The idea is to create markers into google maps which have data (latitude and longitude) .
When i call web service from ajax, the google maps load and show me only an empty map without any marker. Where is the problem ?
<script>
function initialize()
{
var latitude = 38.58;
var longitude = 23.65;
var radius = 8000;
var center = new google.maps.LatLng(latitude, longitude);
var bounds = new google.maps.Circle(
{
center: center, radius: radius
}).getBounds();
var mapOptions =
{
center: center,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map)
{
var jsonString = (function ()
{
var json = null;
$.ajax({
url : 'WebServiceTest.asmx/convertDataTabletoString',
contentType: 'application/json; charset = utf-8',
method: 'get',
dataType: "json",
success: function (data)
{
json = data;
},
error : function(err)
{
alert(err);
}
});
return jsonString;
})();
var circle = new google.maps.Circle({
strokeColor: '#000000',
strokeOpacity: 0.25,
strokeWeight: 1.0,
fillColor: '#ffffff',
fillOpacity: 0.1,
clickable: false,
map: map,
center: center,
radius: radius
});
var bounds = circle.getBounds();
for (i in jsonString) {
var data = jsonString[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
infoBox(map, marker, data);
}
}
function infoBox(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.STREET);
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.STREET);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This can be implemented way faster using the Jquery.parseJSON command. This command is used to parse data which are returned in Json.
Combining the parseJson command and some knowledge that google provided about Placing simple markers can lead to the desire outcome.
Code examples are provided in the links.
I am trying to update the location of a marker with out refreshing the whole page. I have tried to use setTimeout(function() however I am having no luck..
here is my code I have so far..
thanks in advance
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "getjson.php",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
here is my JSON output.
[{"lat":35.6606376,"lng":-80.5048653,"content":"bca"}, {"lat":42.6799504,"lng":-36.4949205,"content":"abc"}]
I would suggest using setInterval rather than setTimeout.
Here is some code that simulates an update via JSON in a fiddle, using your provided JSON with the required "description" member added for each marker:
var map = null;
var gmarkers = [];
var intervalNumber = 0;
setInterval(function () {
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode([{
"lat": 35.6606376 + (0.01 * intervalNumber),
"lng": -80.5048653 + (0.1 * intervalNumber),
"content": "bca",
"description":"first marker"
}, {
"lat": 42.6799504 + (0.01 * intervalNumber),
"lng": -36.4949205 - (0.1 * intervalNumber),
"content": "abc",
"description": "second marker"
}]),
delay: 3
},
onSuccess: function (response) {
update_map(response);
intervalNumber++;
}
}).send();
}, 5000);
update_map = function (data) {
var bounds = new google.maps.LatLngBounds();
// delete all existing markers first
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
// add new markers from the JSON data
for (var i = 0, length = data.length; i < length; i++) {
latLng = new google.maps.LatLng(data[i].lat, data[i].lng);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data[i].title
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
})(marker, data[i]);
gmarkers.push(marker);
}
// zoom the map to show all the markers, may not be desirable.
map.fitBounds(bounds);
};
function initialize() {
// initialize the map on page load.
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// add the markers to the map if they have been loaded already.
if (gmarkers.length > 0) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
https://developers.google.com/maps/documentation/javascript/reference
markerObject.setPosition(latlng:LatLng|LatLngLiteral)
I don't think you need to redraw the map, but in case you do:
google.maps.event.trigger(mapObject, 'resize');
I'm trying to put about 120 marker on a Google Map using ajax populated array of google.maps.LatLng objects
here's my script
<script type ="text/javascript">
$.ajaxSetup({
cache: false
});
var gMapsLoaded = false;
var latlng = [];
var returnValue;
var marker;
var xmlDoc;
$.ajax({
type: "POST",
url: "map.aspx/getLatLng",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
xmlDoc = $.parseXML(response.d);
$(xmlDoc).find("Table").each(function () {
latlng.push(new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text()));
});
//alert(latlng.length.toString());
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(document).ready(function () {
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(24.678517, 46.702267),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
for (var i = 0; i < latlng.length; i++) {
marker = new google.maps.Marker({
map: map,
position: latlng[i]
});
var infowindow = new google.maps.InfoWindow({
content: 'Location info:<br/>Country Name:<br/>LatLng:'
});
google.maps.event.addListener(marker, 'click', function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
}
}
$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
});
</script>
Html
<div id ="map" style="width:850px; bottom:20px; height: 500px;">
</div>
I think i'm missing something here
Should i parse latlng array of google.maps.LatLng objects to LatLng before i assign it to position ?
marker = new google.maps.Marker({
map: map,
position: latlng[i]
});
Your help will be appreciated,
Thanks in advance,
i think the problem is that you aren't taking into account the asynchronous nature of the ajax request.
you need to build the markers after the ajax request has completed.
put your for each loop in a function and call it within 9at the end) of your on success ajax callback.
you will also need to load the ajax after google maps has loaded otherwise you wont be able to create google latlng objects becasue google maps librbary may not be loadded yet.
withjout rewriting everything this may work..
$.ajaxSetup({
cache: false
});
var gMapsLoaded = false;
var latlng = [];
var returnValue;
var marker;
var xmlDoc;
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(document).ready(function () {
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(24.678517, 46.702267),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
$.ajax({
type: "POST",
url: "map.aspx/getLatLng",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
xmlDoc = $.parseXML(response.d);
$(xmlDoc).find("Table").each(function () {
latlng.push(new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text()));
});
for (var i = 0; i < latlng.length; i++) {
marker = new google.maps.Marker({
map: map,
position: latlng[i]
});
var infowindow = new google.maps.InfoWindow({
content: 'Location info:<br/>Country Name:<br/>LatLng:'
});
google.maps.event.addListener(marker, 'click', function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
});
I moved xml processing after map initialization
$(document).ready(function () {
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(24.678517, 46.702267),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
xmlDoc = $.parseXML(stringxml);
$(xmlDoc).find("Table").each(function () {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text())
});
var infowindow = new google.maps.InfoWindow({
content: 'Location info:<br/>Country Name:<br/>LatLng:'
});
google.maps.event.addListener(marker, 'click', function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
});
}
$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
});
And every marker in its proper place.
Thanks guys