Logging JSON values using $.each - javascript

So I have a JSON feed and i'm simply trying to print out some values.
My Javascript below sort of works. But it doesn't look very 'correct'. Is there a better way of doing this please?
JSON
{
"info":[
{
"lon":-2.1,
"lat":55.2
},
{
"lon":-2.12,
"lat":55.23
}
]
}
JavaScript
var jsonURL = "url here";
$.getJSON(jsonURL, function(json1) {
$.each(json1, function(key, data) {
$.each(data, function(key, data){
var latLng = new google.maps.LatLng(
data.lat, data.lon);
var marker = new google.maps.Marker({
position : latLng
});
marker.setMap(map);
});
});
});

You know the "info" attribute exists and don't need a loop to get to it. The inner loop looks good.
$.getJSON(jsonURL, function(json1) {
$.each(json1.info, function(key, data){
var latLng = new google.maps.LatLng(
data.lat, data.lon);
var marker = new google.maps.Marker({
position : latLng
});
marker.setMap(map);
});
});

Related

setMap(null) not working

im trying to delete a Marker from a Map via ajax request.
ajax request looks like this.
$(document).on('click','.deletebtn',function(){
var theid =$(this).parent().attr("id");
var obj = {
id:theid
}
$.ajax({
url:"http://localhost:3000/singleMarker",
method:"post",
contentType:"application/json",
data:JSON.stringify(obj),
dataType:"JSON",
processData: true,
success:function(responseData){
clearMarker(responseData);
}
});
});
the response will reply with a single obj {id:id, {lat:xxx,lng:yyy}}
next i turn the lat lng data into a marker obj:
var clearMarker = function(responseData){
//clearAll Markers from Map
var markers =[];
var temp ={};
var marker;
for(var key in responseData){
//create markers with latlng objs
temp ={lat:responseData[key].pos.lat,lng:responseData[key].pos.lng};
marker = new google.maps.Marker({
position:temp,
map:meineMap
});
markers.push(marker);
}
setMapOnAll(null,markers);
}
then setMapOnAll with map null should delete all markers from the map but is not doing so. why?
function setMapOnAll(map,markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
//markers[i].setVisible(false);
}
}
If you only ever have one marker, there is no need to maintain an array of markers (or to call setMapOnAll), move the marker declaration out of the clearMarker function, if the marker exists, set its map property to null, otherwise, it is the first marker, just create it.
var marker;
var clearMarker = function(responseData){
//clearAll Markers from Map
var temp ={};
for(var key in responseData){
//create markers with latlng objs
temp ={lat:responseData[key].pos.lat,lng:responseData[key].pos.lng};
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position:temp,
map:meineMap
});
}
}

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

How to update map data throug ajax

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.

Google Map Marker not working when from DB

I'm starting to learn Google Map. It's strange that when statically declared, markers are working and being displayed, but when they come from DB, they aren't being drawn on map.
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
I have the entire code here, maybe I am missing something? I even used console log and I successfully pass all data from ajax to markers variable.
I think I got this code somewhere here in SO and modified it to fit in for my DB calls for records. I hope you can help me out on this one. Thank you!
<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?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
var global_markers = [];
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(15.058607, 120.660884);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
type: 'GET',
url: 'control_panel/get_device_list_ajax',
success:
function (data) {
data = JSON.parse(data);
if (data['success']){
var device = data['device_list'];
device.forEach(function (dev) {
markers.push([dev['dev_geolat'], dev['dev_geolng'], dev['dev_name']]);
//console.log(markers);
});
addMarker();
} else {
}
}
});
}
function addMarker() {
console.log(markers);
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
</script>
EDIT
Here is the jsfiddle I used to work with this one http://jsfiddle.net/kjy112/ZLuTg/ (thank you to the one that lead me to this)
Could be related to the way you accessing to json rendered by ajax
markers.push([dev.dev_geolat, dev.dev_geolng, dev.dev_name]);
or the json content
I don't know how to close this question as I overlooked some problems on my DB but I'll be posting my answer if someone may come with the same problem (well, I am not sure about that hehe)
I get the same response from AJAX of the values in DB and I am not able to draw markers on MAP, I found that db->table->fields LAT LNG are referenced with a data type of DECIMAL (7,5) and changed it to FLOAT (10, 6) as to what is found in this GOOGLE MAP Tutorial - Using PHP/MySQL with Google Maps.
The issue at the field before was that higher values tend to be saved as 99.999999 instead of the actual value (e.g. 120.XXXXX) .

Google Map Markers not displaying in MVC

I am trying to render Google map with Latitude and Longitude from my MVC Model by using different examples. Google Map is displaying fine but it is not displaying the markers. I am very new to the Google Maps and feeling completely clueless about it. Can please anyone tell me how I can get the markers?
My MVC view is as follow
if (Model.WidgetType == "Map")
{
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$.get("/Home/GetMapLocations", function(data){
$.each(data, function(i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});
});
#*var data = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.lstMapLocations));
$.each(data, function (i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});*#
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
}
MVC Controller is as follow
public ActionResult GetMapLocations()
{
var lstMapLocations = new List<MapLocation>();
var mapLocationModel1 = new MapLocation
{
EngineerName = "Engineer1",
SiteName = "Site1",
Latitude = 51.507351,
Longitude = -0.127758,
LstDouble = new List<double>()
};
var mapLocationModel2 = new MapLocation
{
EngineerName = "Engineer2",
SiteName = "Site2",
Latitude = 51.481728,
Longitude = -0.613576,
LstDouble = new List<double>()
};
var mapLocationModel3 = new MapLocation
{
EngineerName = "Engineer3",
SiteName = "Site3",
Latitude = 51.628611,
Longitude = -0.748229,
LstDouble = new List<double>()
};
var mapLocationModel4 = new MapLocation
{
EngineerName = "Engineer4",
SiteName = "Site4",
Latitude = 51.26654,
Longitude = -1.092396,
LstDouble = new List<double>()
};
lstMapLocations.Add(mapLocationModel1);
lstMapLocations.Add(mapLocationModel2);
lstMapLocations.Add(mapLocationModel3);
lstMapLocations.Add(mapLocationModel4);
foreach(var item in lstMapLocations)
{
item.LstDouble.Add(item.Latitude);
item.LstDouble.Add(item.Longitude);
item.LatLong = item.LstDouble.ToArray();
}
return Json(lstMapLocations);
}
I have found a work around to my problem and thought to share it for those who may stumble upon a similar issue. Courtesy stack overflow post particularly the answer posted by Atish Dipongkor. There may well be a better alternative to this problem but this approach has resolve my problem. I have made little change in that answer as Atish has used apostrophes while retrieving data from model which can break the functionality if any of the model field has string data with apostrophe in it. My appended solution with the above dummy data (in my question) is as follow
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 8,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
#foreach (var item in Model.lstMapLocations)
{
<text>
var markerLatLong = new google.maps.LatLng(#(item.Latitude), #(item.Longitude));
var markerTitle = #Html.Raw(Json.Encode(item.EngineerName));
var markerContentString = #Html.Raw(Json.Encode(item.EngineerName)) + " At " + #Html.Raw(Json.Encode(item.SiteName));
var infowindow = new google.maps.InfoWindow({
content: markerContentString
});
var marker = new google.maps.Marker({
position: markerLatLong,
title: markerTitle,
map: map,
content: markerContentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>

Categories