I'm writing a program with AmMaps where I want a user to click on a map of a country, and to be able to select and save locations.
I'm stuck on getting data back after the user clicks on the map. I used the "clickMapObject" event on another page, but in this case they aren't clicking anything.
<script>
var map;
$(document).ready(function () {
map = new AmCharts.AmMap();
map.pathToImages = "ammap/images/";
var dataProvider = {
mapVar: AmCharts.maps.irelandHigh,
getAreasFromMap: false,
};
map.dataProvider = dataProvider;
map.areasSettings = {
autoZoom: false,
color: "#CDCDCD",
colorSolid: "#5EB7DE",
selectedColor: "",
outlineColor: "#666666",
rollOverColor: "#88CAE7",
rollOverOutlineColor: "#FFFFFF",
selectable: false,
};
map.addListener("click", click);
map.write("mapdiv");
function click() {
//Can i get long and lat here?
};
});
</script>
I didn't use this map control, but I ever used google map, so I think maybe you can try this:
map.addListener("click", function (e) {
//get lat and lng from e object
var latLng = e.latLng;
});
Ok, I found it.
Code:
map.addListener("click", function (event) {
var s = map.getDevInfo();
// then you can access s.Longitude or zoomLongitude
});
Related
I am using Markclusterer extension with Google Map API v3 and i ran into certain trouble, The map shows perfectly and also the cluster works but my problem is that certain address share the same Longitude and latitude hence groups the address and show the number of address as a group but i cannot zoom any further into the group. I have tried to increase the zoom but that did not help. Any ideals or solution would be appreciated thanks.
var map;
var markers = new Array();
var locations = new Array();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var center = new google.maps.LatLng(<%= GetCenterLatLng() %>);
// var center = new google.maps.LatLng(52.6500, 1.2800);
var infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
initialiseMarkers();
var mcOptions = { gridSize: 50, maxZoom: 15 };
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
}
function addMarker(marker, content) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content); // this is the trick: html attribute on markerOptions :), I used a array here
infowindow.open(map, this);
});
}
<script type="text/javascript">
var script = '<script type="text/javascript" src="../Scripts/markerclusterer';
if (document.location.search.indexOf('compiled') !== -1) {
script += '_compiled';
}
script += '.js"><' + '/script>';
document.write(script);
</script>
if you have any question please contact me thanks
After days of cranking my brain and maybe some sleepless night. The solution was to group address that contain the same longitude and latitude as one marker and on click it shows all the address within the same vicinity on the popup window(infoWindow)
I have a problem in How to use javascript variables in C# and vise versa : I have this Model passing to the view:
public List<Tache> Get_List_Tache()
{
Equipe _equipe = new Equipe();
List<Tache> liste_initiale = _equipe.Get_List_tache();
return liste_initiale;
}
It's a list of objects Tache in which I'd like to use it's three fields Tache_description, Begin_date and End_date.
In my JavaScript code I have this function and it works fine:
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#foreach (var m in Model.Get_List_Tache())
{
#:{title : #m.Tache_description , start: #m.Begin_date , end : #m.Begin_date }
}
]
});
});
</script>
The values of the array events are just for test, and I need to fill events by the value of the Model. For each element like this: title = Tache_description, start = Begin_date and end = End_date.
So how can I do this task? Any suggestions?
Try this,
foreach (var item in YourList)
{
events: [{ title: '#item.title', start: '#item.start', end: '#item.end'}]
}
So, in this code just replace name your model entity.
Make a foreach razor loop within javascript :
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#
{
bool isFirst = true;
}
#foreach(var m in Model)
{
if(!isFirst)
{
#:,
}
#:{title: #m.Tache_description, ...<other properties here>}
isFirst = false;
}
]
});
For title, you can do title = "#Tache_description"
Not sure about the format/type of your Begin_date and End_date, you may need some function to read the date into a javascript format. Shouldnt be that hard.
Loop through each element and add the elements to the events array. It is something like...
events = new Array()
#foreach(tache in list){
item = { blah : blah, blah : blah };
events.push(item);
}
for each c# item in this c# list, write these lines of javascript. You may end up with a very long javascript code block, but it should do the trick. Above is pseudocode.
To add to Darin's answer: If you need the server-side variables in an external JavaScript file, take a look this blog post: Generating External JavaScript Files Using Partial Razor Views
1: if your model is expecting the list of Tache then you have the whole list you can manipulate.
2: you can get the data using jquery ajax as json data by calling your action Get_List_Tache().
Assuming this javascript is inline in your page you could do the following:
#model IList<Tache>
<script type="text/javascript">
var events = #Html.Raw(Json.Encode(Model.Select(x => new { title = x.Description, start = x.Begin.ToString("o"), end = x.End.ToString("o") })));
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: events
});
</script>
This example assumes that your Tache model has properties Description, Begin and End:
public class Tache
{
public string Description { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
}
And if this script is in a separate javascript file you could still set a global events variable in your view which will later be used by your script. Alternatively you could fetch this model using an AJAX call.
$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/
I want to implement the google map in my page. In my page there is one textbox and one button. User need to enter the location for which he want to have the map. Then on clicking of the button the map should appear in a div.
Could anyone provide me the steos to do so?
Thanks in advance.
This is quite easy if you use the google api js file. As a reference you can use this link:
http://code.google.com/apis/maps/documentation/javascript/reference.html
Add the jQuery and GoogleMaps API library in the HEAD section:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
Add new tag to create the google maps object in the div:
var geocoder;
var map;
$(document).ready(function() {
/* Create the geocoder */
geocoder = new google.maps.Geocoder();
/* Some initial data for the map */
mapOptions = {
zoom: 10,
center: new google.maps.LatLng(48.13, 13.58),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
};
Add on click handler for the button:
$('#idMyButton').click(function() {
if (geocoder) {
var address = $('#idMyTextbox').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
/* Position the map */
map.panTo(results[0].geometry.location);
/* Put a marker */
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address,
});
}
else
alert('Address not found');
};
}
});
I hope this will help.
You some C# control for .NET, for example this one: http://sourceforge.net/projects/gmapdotnetctl/
I am using ASP.NET MVC in C#
I have a page where the user can move different Widgets around the page, and I now need a method to save the state of the widgets. I am using jQuery in the HTML page, and the jQuery posts the new page layout using JSON. I am unsure how to read the JSON in the controller.
The code I'm using is based on this example here - http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/, but the code for saving the result is in PHP.
jQUERY
<script type="text/javascript" >
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
//Save state on change of collapse state of panel
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
start: function (event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find('.dragbox-content').toggle();
},
stop: function (event, ui) {
ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
//Pass sortorder variable to server using ajax to save state
$.post('/Widgets/SaveLayout', 'data=' + $.toJSON(sortorder), function (response) {
if (response == "success")
$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#console').fadeOut(1000);
}, 2000);
});
alert(sortorder);
}
I am willing to consider alternative ways to do this, as I may not have chosen the best way to do this.
Phil Haack's blog post http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx specifically handles the problem you are trying to solve and it works great.
Hope this helps.
Why not use a cookie? This would save you from having to pull that data back and forth from the server so much.