How to update map data throug ajax - javascript

I am trying to update map data through ajax but ist's not working here is my code:
$(document).ready(function() {
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/users/online-peoples'; ?>",
type:"POST",
})
.done(function(result){
var icon1 = 'https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0';
if(result){
var map;
function initMap() {
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng('30.7333','76.7794'),
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var online =result;
var mapIcons = ['https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0'];
var person = {3:"Customer1 : ", 4:"Driver1 : "};
var arr = [];
var marker, i;
for (i = 0; i < online.length; i++)
{
console.log(online[i]);
arr.push(new google.maps.LatLng(online[i][0], online[i][0]));
marker = new google.maps.Marker({
position: new google.maps.LatLng(online[i][0], online[i][1]),
icon:mapIcons[0],
suppressMarkers: true,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(person[online[i][4]]+online[i][2]+', Phone : '+online[i][5]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
}
});
}
setInterval(makeRequest, (10 * 1000));
});
The above code update map icons and date every 10 secondas but it's not working.Where i am doing wrong ?
This is my data :
[
["30.740395","76.7804482","Dbd Dbdhdh","1",4],
["30.740395","76.7804482","Sam Sam","1",4],
["30.7404344","76.7804032","Sumit Kumar","1",4],
["30.74041018","76.78060575","Chetan Nagrath","3",4],
["30.7403555","76.7804933","Sahil Kapoor","2",4],
["30.7403648","76.7805835","paras kumar",1,3]
]

You are not initializing your map. Since its inside initMap map function no one is calling it.
And there is no need to initialize every time when you got the data from the server. Just initialize once and use the same map object for your other works also.
And be careful while getting the data, You are trying to get the data in the index 5. But the array has only 0 to 4.
Try in the below fashion.
$(document).ready(function() {
function makeRequest() {
$.ajax({
url : "url",
type : "POST",
}).done(function(result) {
if (result) {
console.log("You Got your data", result);
}
});
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 12,
center : new google.maps.LatLng('30.7333', '76.7794'),
mapTypeControlOptions : {
mapTypeIds : [ 'roadmap' ]
}
});
setInterval(makeRequest, (10 * 1000));
});
Here you will get data after 10 second. If you want at the first time itself means call makeRequest after initialization of map once.

Related

Laravel fetch longitude and latitude from database and display markers on Google Map

Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}

Iteration in Javascript doesn't run [duplicate]

I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"

how to use json ajax for google map markers

I try to use the Json Ajax for google map markers.So after clicking on the button run Ajax, I get a problem with it. it's not display markers
Should change be made?
Where is my problem?
this is My Action after run ajax:
[HttpPost]
public ActionResult AsMapAjax(string jobid,string subid,string Searchitem)
{
string markers = "[";
foreach (var item in UnitOfWork.WD.GetAll())
{
markers += "{";
markers += string.Format("'title': '{0}',", "Test");
markers += string.Format("'lat': '{0}',", item.Lat);
markers += string.Format("'lng': '{0}',", item.Lng);
markers += string.Format("'description': '{0}'", "www.google.com");
markers += "},";
}
markers += "];";
var mark= new MvcHtmlString(markers);
return Json(new { success = true, responseText = mark }, JsonRequestBehavior.AllowGet);
}
}
and my jquery ajax(scripts):
navigator.geolocation.getCurrentPosition(function (p) {
var latlng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var mapOptions = {
center: latlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//You re Here
var iconoMarca = "../../images/URHere.gif";
mymarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
map: map,
icon: iconoMarca,
position: latlng
});
$('#prt').on('click', function () {
var Subid = document.getElementById("bluee").value;
var jobid = document.getElementById("Jobs").value;
var Searchitem = document.getElementById("SearchItem").value;
$.ajax({
type: "post",
url: "/My/AsMapAjax",
dataType: 'json',
data: { subid:Subid,jobid:jobid,Searchitem:Searchitem},
success: function (response) {
if (response != null && response.success) {
//alert(response.responseText);
markers=response.responseText;
} else {
alert("there is a problem!");
}
},
error: function (response) {
alert("Sorry!try again please.");
}
}
)
///////
//label
var numberMarkerImg = {
url: '../../images/shapemarker.png',
size: new google.maps.Size(32, 38),
scaledSize: new google.maps.Size(32, 38),
labelOrigin: new google.maps.Point(21,42)
};
var markerLabel = 'Test';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
//label
label:markerLabel ,
title: data.title,
icon:numberMarkerImg,
animation: google.maps.Animation.DROP
});
( function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
window.location.href = "/My/sargarmi";
});
})
(marker, data);
}
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
but the markers not display ! how to fix this problem?
or is other way for this question?
thanks a lot
Your question does not explain what specific problem you are experiencing. So i am going to give you a simple - working solution which improves some of the stuff you did.
Let's start with your server method. You are building the stringified version of a json array by string concatenation. That is unnecessary and error prone. Why not let the JSON serializer which is part of the mvc framework to do that for you ?
Create a simple class to represent your marker
public class Marker
{
public string Title { set; get; }
public double Lat { set; get; }
public double Lng { set; get; }
}
Now in your action method, Build a list of this Marker class and you can pass that to the Json method.
[System.Web.Mvc.HttpPost]
public ActionResult AsMapAjax(string jobid, string subid, string Searchitem)
{
//Hard coded for demo. You may replace with values from db
var list = new List<Marker>
{
new Marker() { Title="AA" ,Lat = -33.890542, Lng=151.274856 },
new Marker() { Title="BB", Lat = -33.923036, Lng=151.259052 },
new Marker() { Title="CC" ,Lat = -34.028249, Lng=151.157507 },
};
return Json(new { success = true, responseText = list });
}
Now in your client side, you make the ajax call to this action method, read the response coming back and add markers.
$(function() {
$('#prt').on('click', function() {
initMap();
});
});
function initMap() {
//read the parameter values you want to send to server
var searchItem =$("#SearchItem").val();
var jobs=$("#Jobs").val();
var subid = $("#bluee").val();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 8
});
var url = "#Url.Action("AsMapAjax", "Home")";
$.post(url, { searchTerm: searchItem,jobid: jobs,subid : subid },function(res) {
if (res.success) {
var latLng;
$.each(res.responseText,function(i, item) {
latLng = new google.maps.LatLng(item.Lat, item.Lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
});
map.setCenter(latLng);
}
});
}
I am using the Url.Action method to generate the correct relative url to the action method as my script was inside a razor code block. If you are using this code in an external javascript file, follow the solution described in this post to handle that case

Uncaught TypeError: Cannot read property 'targetLat' of undefined

well i just put some markers on google map and it works as i want and marker is displayed as required on the map but i get this error in the console i don't know why which makes the app runs on android but not on windows phone
function initMap() {
var map;
var faisalabad = { lat: 30.044281, lng: 31.340002 };
$('#locaitonBtn').click(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(latlng);
});
}
})
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: faisalabad,
disableDefaultUI: true
});
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i));
}
}
})
}
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
var myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i, data) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i, data));
}
}
});
changed 3 things:
var i = 0 in for statement
var myMarker = new google.maps.Marker ... (it's not a global)
injecting data to the anonymous click listener function because it has no scope on the data object.
i'm not sure this works because i have no test envoirement for it. but hope it helps you to figure out the failure.
i think the first point was the failure because you tried to use a global i in your for loop and reset it anywhere else in your code. so the array index returns undefined
Well I couldn't solve the problem or find an answer to it anywhere so i added the success function to a try catch block so it don't console the error and i can run the app now on windows phone

Refresh JavaScript and Ajax call to controller after 3 seconds without any click in Razor View in MVC 4

Controller Action :
public ActionResult googlemap()
{
return View();
}
It will call the googlemap.cshtml View.
So Ajax Call and JavaScript code in googlemap.cshtml View :
#{
ViewBag.Title = "Google Map";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCM7G5ruvunb0K7qxm6jb1TssJUwROqs-g" type="text/javascript"></script>
<script type="text/javascript">
var myMarkers = [];
window.onload = function () {
$.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>
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);
}
So here I wants that my Ajax call is done repeatedly after each 3 seconds automatically to the JsonResult action in controller , and controller get the latest values and send back to the Ajax.
var myMarkers = [];
window.onload = function () {
DisplayMap();
}
function DisplayMap() {
$.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
}
setTimeout(function () {
DisplayMap();
}, 3000);// JavaScript source code
Try this:
var searchActiveTVInterval = null;
$(document).ready(function () {
clearInterval(searchActiveTVInterval);
searchActiveTVInterval = setInterval("SearchActiveTV()", 3000);
});
function SearchActiveTV() {
console.log(1);
//your AJAX Call
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
window.setInterval(function(){
/// call your ajax function here
}, 3000);

Categories