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
Related
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
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.
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>
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);
});
});
Using code that was posted on here, I'm trying to map markers from an XML file to a Google Map in a JSP using the Google Maps Javascript API V3.
My markers file has the following format:
<markers>
<marker>
<id>0</id>
<lat>53341428</lat>
<lng>-6246720</lng>
<name>Fenian Street</name>
<number>63</number>
</marker>
<marker>
<id>1</id>
<lat>53346637</lat>
<lng>-6246154</lng>
<name>City Quay</name>
<number>99</number>
</marker>
And the code is:
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'`enter code here`
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl( "markers.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = markers[i].getElementsByTagName("id")[0];
var point = new google.maps.LatLng(
parseFloat(markers[i].getElementsByTagName("lat")[0]),
parseFloat(markers[i].getElementsByTagName("lng")[0]));
var name = markers[i].getElementsByTagName("name")[0];
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: image
});
marker.setMap(map);
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();
}
function doNothing() {
}
</script>
When I load the page, I see an error in he console: InvalidValueError: setTitle: not a string
What am I doing wrong? The markers are not appearing on the map.
You are getting that error because "name" is not a string, it is an XML DOM object. There is a function nodeValue that can be used to get the string content out of an XML DOM element.
Also, your latitude and longitude are not valid, they are not in decimal degrees.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// downloadUrl( "markers.xml", function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlString);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = nodeValue(markers[i].getElementsByTagName("id")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName("lat")[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName("lng")[0])));
var name = nodeValue(markers[i].getElementsByTagName("name")[0]);
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: ""+name /*,
icon: image */
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
// });
}
where nodeValue was "borrowed" from geoxml3:
//nodeValue: Extract the text value of a DOM node, with leading and trailing whitespace trimmed
function nodeValue (node, defVal) {
var retStr="";
if (!node) {
return (typeof defVal === 'undefined' || defVal === null) ? '' : defVal;
}
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
};
working fiddle