Bing Map Integration with ASP.NET MVC 4.5 - javascript

im having trouble with getting pushpins on my map.
Im using Bing maps and i want to show some coordinates on it. i have followed a tutorial on youtube but still don't manage to make it.
The link is here https://www.youtube.com/watch?v=uVeuib8_MWw&t=2s
So this is what i got!
In my class model i got
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models
{
public class Locations
{
public string latitude { get; set;}
public string longitude { get; set;}
public Locations(string latitude, string longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
}
In my controller i have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Map.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetLocations()
{
var locations = new List<Models.Locations>()
{
new Models.Locations("12.505353","55.335292"),
new Models.Locations("13.505353","55.485292"),
new Models.Locations("13.655353","55.665292")
};
return Json(locations, JsonRequestBehavior.AllowGet);
}
}
}
And at the end its the view. Here is the map aswell and the pushpins.
#{
ViewBag.Title = "Home Page";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
$(document).ready(function () {
var map = null;
function LoadMap() {
map = new Microsoft.Maps.Map(
document.getElementById('myMap'),
{
credentials: "Bing map key"
});
}
LoadMap();
$('#btnShowLocations').click(function () {
var url = "/Home/GetLocations";
$.getJSON(url, null, function (data) {
$.each(data, function (index, LocationData) {
var pushpin = new Microsoft.Maps.pushpin(map.getCenter(), null);
pushpin.setLocation(new Microsoft.Maps.Location(
LocationData.latitude,
LocationData.longitude));
map.entities.push(pushpin);
map.setView({
zoom: 4, center: new Microsoft.Maps.Location(23.505353, 78.485292)
});
});
});
});
});
</script>
<h2>Bing Map integration in ASP.NET</h2>
<input type="button" id="btnShowLocations" value ="Show All Locations" />
<div id="myMap" style="position:relative; width:600px; height:600px;">
</div>
The map is working and i get no errors. My problem is that when i press the button nothing happens. What i want is that when the button is pressed there should be 3 pushpins on the given coordinates.
Thanks so very much for reading! i hope i can get it to work!

A few issues and recommendations:
The main issue is that your latitude and longitude values are strings and are never parsed as floats/numbers. As such the map is getting string values for locations when it is expecting numbers.
Your code is using Bing Maps V7 which was replaced by V8 a while ago. V7 is nearing end of life and will be turned off at the end of June. This is the new map script URL to V8: http://www.bing.com/api/maps/mapcontrol
document.ready will fire long before the map script will load as it loads asynchronously. In fact, document.ready sometimes will fire before the whole page is loaded which means your map div might not event be available. I suggest using the callback parameter of the map script UR: for example: http://www.bing.com/api/maps/mapcontrol?callback=LoadMap
You are setting the view of the map in a loop, this should work, but will cause a lot of extra refreshes for nothing which will cost you in load performance.
A couple of recommendations:
add your pushpins to an array then add the array to the map. This will reduce the number of refreshes needed.
move your scripts to the bottom of the page and call the map script URL last since it loads asynchronously. When the map script is cached it and you press "refresh", the callback gets called instantly and often before the rest of your code is loaded. Moving this line of code to the bottom allows your page to load the fastest it can.
Here is some suggested modifications to your code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models
{
public class Locations
{
public double latitude { get; set;}
public double longitude { get; set;}
public Locations(double latitude, double longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
}
Your controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Map.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetLocations()
{
var locations = new List<Models.Locations>()
{
new Models.Locations(12.505353,55.335292),
new Models.Locations(13.505353,55.485292),
new Models.Locations(13.655353,55.665292)
};
return Json(locations, JsonRequestBehavior.AllowGet);
}
}
}
Your view:
#{
ViewBag.Title = "Home Page";
}
<h2>Bing Map integration in ASP.NET</h2>
<input type="button" id="btnShowLocations" value ="Show All Locations" />
<div id="myMap" style="position:relative; width:600px; height:600px;"></div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var map = null;
function LoadMap() {
map = new Microsoft.Maps.Map('#myMap', {
credentials: "Bing map key"
});
}
$('#btnShowLocations').click(function () {
var url = "/Home/GetLocations";
$.getJSON(url, null, function (data) {
var pins = [];
$.each(data, function (index, LocationData) {
var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(
LocationData.latitude,
LocationData.longitude));
pins.push(pushpin);
});
map.entities.push(pins);
map.setView({
zoom: 4, center: new Microsoft.Maps.Location(23.505353, 78.485292)
});
});
});
</script>
<script type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?callback=LoadMap" async defer></script>

Related

Does new versions of google map's javascript versions work on JavaFx-WebView

I am trying to load google map on JavaFx-WebView, and it doesn't show anything except background color of html body that i have coded on html file.
Also i tried some examples on Google search, all the result were older. None of it works.
My Java version is "1.8.0_121"
I wrote a html file & run it. It loaded google maps successfully.
Then i load the html file to webview using webEngine.load("path") method.
it doesn't show anything except backgound color.
After that I tried
http://rterp.github.io/GMapsFX
runs ClusteredMainApp.java (put my google api key)
consoles outputs are:
"hier"
"clustererimages/m"
"Hide directions called"
"loadMapLibrary"
"loadMapLibrary done"
"initMap"
"LatLong: (47.606189, -122.33584200000001)"
"netscape.javascript.JSException: Error: The Google Maps JavaScript
API does not support this browser. (undefined,0)"
Also i couldn't find any solutions for this error
Html File
CSS:
#map_canvas { height: 100%; background-color: blue; }
javascript:
function initialize() {
var latlng = new google.maps.LatLng(37.39822, -121.9643936);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
backgroundColor: "#666970"
};
document.geocoder = new google.maps.Geocoder();
document.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
html:
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
JavaFX:
public class WebMap extends Application {
#Override public void start(Stage stage) {
// create web engine and view
final WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
webEngine.load(getClass().getResource("WebMap.html").toString());
// create scene
stage.setTitle("Web Map");
Scene scene = new Scene(webView,1000,700, Color.web("#666970"));
stage.setScene(scene);
// show stage
stage.show();
}
public static void main(String[] args){
Application.launch(args);
}
}
Google maps API dropped support for older browsers which started causing the "The Google Maps JavaScript API does not support this browser." error. Look at https://developers.google.com/maps/documentation/javascript/releases and https://developers.google.com/maps/documentation/javascript/versions.
The library you are using is using version 3.exp (experimental).
Running on a newer Java version will fix this (for now).
If you want to use GMapsFX you can download the sample code from your link.
If you look closer you will see the lib got an class GoogleMapView and this contains is own WebView
some code from GMapsFX
public class GoogleMapView extends AnchorPane {
private static final Logger LOG = LoggerFactory.getLogger(GoogleMapView.class);
protected static final String GOOGLE_MAPS_API_LINK = "https://maps.googleapis.com/maps/api/js?v=3.exp";
protected static final String GOOGLE_MAPS_API_VERSION = "3.exp";
private boolean usingCustomHtml;
protected String language;
protected final String region;
protected String key;
protected WebView webview; <-- Own WebView
protected JavaFxWebEngine webengine;
protected boolean initialized = false;
protected final CyclicBarrier barrier = new CyclicBarrier(2);
protected final List<MapComponentInitializedListener> mapInitializedListeners = new ArrayList<>();
protected final List<MapReadyListener> mapReadyListeners = new ArrayList<>();
protected GoogleMap map;
protected DirectionsPane direc;
protected boolean disableDoubleClick = false;
So if you want to use the lib you should not create your own WebView.
You could start with the Sample
import com.lynden.gmapsfx.GoogleMapView;
import com.lynden.gmapsfx.javascript.event.GMapMouseEvent;
import com.lynden.gmapsfx.javascript.event.UIEventType;
import com.lynden.gmapsfx.javascript.object.GoogleMap;
import com.lynden.gmapsfx.javascript.object.LatLong;
import com.lynden.gmapsfx.javascript.object.MapOptions;
import com.lynden.gmapsfx.javascript.object.MapTypeIdEnum;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.web.WebView;
public class LatLongFXMLController implements Initializable {
#FXML
private Label latitudeLabel;
#FXML
private Label longitudeLabel;
#FXML
private GoogleMapView googleMapView;
private GoogleMap map;
private DecimalFormat formatter = new DecimalFormat("###.00000");
#Override
public void initialize(URL url, ResourceBundle rb) {
googleMapView.addMapInitializedListener(() -> configureMap());
}
protected void configureMap() {
MapOptions mapOptions = new MapOptions();
mapOptions.center(new LatLong(47.6097, -122.3331))
.mapType(MapTypeIdEnum.ROADMAP)
.zoom(9);
map = googleMapView.createMap(mapOptions, false);
map.addMouseEventHandler(UIEventType.click, (GMapMouseEvent event) -> {
LatLong latLong = event.getLatLong();
latitudeLabel.setText(formatter.format(latLong.getLatitude()));
longitudeLabel.setText(formatter.format(latLong.getLongitude()));
});
}
}

(Apache Wicket) Set java atrribute from a js function

I am brand new on Apache Wicket and I need to set value on a Java attribute. This value comes from a var on JS filled by a specific function from a specific GIS lib (https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html). This setting must be triggered by some component behavior.
Here is a simplified example code:
Wicket web page:
public class MapPage extends WebPage {
private static final long serialVersionUID = 1L;
private Integer coordinates;
// getters and setters
}
Wicket html:
<html xmlns:wicket="http://wicket.apache.org">
<head>
<!-- metas, scripts, and css imports -->
</head>
<body>
<script>
// component declarations
var coordinates = ''
map.on('draw:edited', function (e) {
e.layers.eachLayer(function(layer) {
coordinates = toWKT(layer);
// send coordinates to coordinates java attribute ??? how??
});
});
</script>
</body>
Thanks a lot!
This is a piece of code from one of my projects, where I want to handle a click on a (HighCharts) chart. It passes data to Wicket and Wicket then updates another panel to display details related to the click.
The relevant javascript part, where interactionurl is actually the callbackScript that is generated by the behavior later on:
interactionurl(JSON.stringify(myDataToPass));
The behaviour:
this.add( this.interactionbehavior = new AbstractDefaultAjaxBehavior()
{
#Override
protected void respond( final AjaxRequestTarget target )
{
RequestCycle cycle = RequestCycle.get();
WebRequest webRequest = (WebRequest) cycle.getRequest();
String param1 = webRequest.getQueryParameters().getParameterValue( "mydict" ).toString( "" );
//param1 contains the JSON map passed from javascript.
//you can also do stuff now, like replacing components using ajax
}
#Override
protected void updateAjaxAttributes( AjaxRequestAttributes attributes )
{
super.updateAjaxAttributes( attributes );
attributes.getExtraParameters().put( "mydict", "__PLACEHOLDER__" );
}
#Override
public CharSequence getCallbackScript()
{
String script = super.getCallbackScript().toString().replace( "\"__PLACEHOLDER__\"", "data" );
return script;
}
} );
You only need to pass the interaction url to the page on some moment. For this you can use renderHead in the component that has the behaviour:
#Override
public void renderHead( final IHeaderResponse response )
{
...
//use the `setupCallback` to store the callback script somewhere.., I store it in 'interactionurl'
String script = String.format( " setupCallback(this.interactionbehavior.getCallbackScript()); ");
response.render( OnDomReadyHeaderItem.forScript( script )
}

Trying to create an event calendar using the datepicker javascript

I am attempting to use the javascript datepicker to help in showing a calendar and being able to select a date to add/view/edit an event on that date.
I currently have a view that shows the datepicker calender in a div
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Calendar</title>
<link rel="stylesheet" href="/Content/themes/base/jquery-ui.css">
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
</head>
<body>
Date: <div id="datepicker"></div>
</body>
</html>
I have a model Todays events that will show the events for the day
namespace TryEvents2.Models
{
public class TodaysEventsViewModel
{
public List<Event> events;
}
}
a model for the specific events
namespace TryEvents2.Models
{
[Bind(Exclude = "Id")]
public class Event
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[DisplayName("Start Date")]
public DateTime Start { get; set; }
[DisplayName("End Date")]
public DateTime End { get; set; }
[DisplayName("Event Details")]
public string Message { get; set; }
[DisplayName("User")]
public string UserName { get; set; }
public void setEvent()
{
}
}
}
a model for the database calendar entities
namespace TryEvents2.Models
{
public class CalendarEntities : DbContext
{
public DbSet<Event> Events { get; set; }
}
}
I have a home controller of the following
namespace TryEvents2.Controllers
{
public class HomeController : Controller
{
CalendarEntities db = new CalendarEntities();
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
public PartialViewResult GetWEntitiesByDate(DateTime date)
{
var entities = db.Events.Where(x => x.Start == date.Date);
var todaysEvents = new TodaysEventsViewModel {events = entities.ToList() };
return PartialView("_TodaysEvents", todaysEvents);
}
}
}
I am having difficulties going from here on creating the methods necessary to CRUD the calendar events and the view that would be displaying them. I am wanting to make the standard datepicker element bigger and have a popup window for the event detail display.
Can anyone help with this?
In my few experience doing something like that is quite difficult with jquery UI datepicker. If you want a calendar to works as a datepicker and able to edit events and shows depending on the day I think the best solution for you is Arshaw Fullcalendar
FullCalendar
This is a calendar (not a datepicker) but you can create custom events to make it works as a datepicker-calendar for your purposes. You can choose a date an render your events from a specific date. You are using MVC so for bringing the date you need JSON like this
public ActionResult GetEvents()
{
//code to return the events from DB
return Json(evevtsObject,JsonRequestBehavior.AllowGet);
}
And for the events to load on the calendar you need to call the "events" function from the calendar.
events: function (startdate, enddate, callback) {
var url = "Controller/GetEvents";
$.getJSON(url,
function (result) {
if (result != null) {
for (i in result) {
var calEvent = result[i];
calEvent.startdate = new Date(parseInt(calEvent.startdate.replace("/Date(", "").replace(")/", ""), 10));
calEvent.end = new Date(parseInt(calEvent.enddate.replace("/Date(", "").replace(")/", ""), 10));
}
}
var calevents = result;
callback(calevents);
});
}
Hope this helps.

getting [Object Object] in place of String in Javascript visualforce page

Here is my controller class:
global class MyJSController {
public static String objj { get; set; }
#RemoteAction
public static String getObject_name(){
return objj;
}
#RemoteAction
public static void setObject_name(String s){
objj=s;
}
public String accountName { get; set; }
public static Account account { get; set; }
public static List<Order__c> order{get;set;}
public static List<Units__C>unit{get;set;}
public static List<Widget__c> widget{get;set;}
public MyJSController() {
setObject_name('Order');
} // empty constructor
#RemoteAction
global static Account getAccount(String accountName) {
account = [SELECT id, name, phone, type, numberofemployees
FROM Account WHERE name = :accountName];
return account;
}
#RemoteAction
global static Order__c[] getOrder(){
return ([SELECT id,Name,Date__c,Inbound_Orders__c,Outbound_Orders__c from Order__c]);
}
#RemoteAction
global static List<Units__c> getUnits(){
unit=[SELECT id,Name,Date__c,Inbound_Units__c,Outbound_Units__c from Units__c];
return unit;
}
#RemoteAction
global static List<Widget__c> getWidget(){
widget=[SELECT id,Name,Date__c,Inbound_Widgets__c,Outbound_Widgets__c from Widget__c];
return widget;
}
}
And here is my visualforce page:
<apex:page controller="MyJSController">
<apex:form >
<apex:selectList id="chooseColor" value="{!object_name}" size="1" onchange="initCharts()" >
<apex:selectOption itemValue="Order" itemLabel="Order"/>
<apex:selectOption itemValue="Unit" itemLabel="Unit"/>
<apex:selectOption itemValue="Widget" itemLabel="Widget"/>
</apex:selectList>
</apex:form>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initCharts);
function initCharts() {
// Following the usual Remoting syntax
// [<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) {...}
// namespace : abhinav
// controller : GoogleChartsController
// method : loadOpps
MyJSController.getOrder(
function(result, event){
// load Column chart
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
for(var i =0; i<result.length;i++){
var r = result[i];
data.addRow([r.Name,r.Inbound_Orders__c]);
}
var data1=new google.visualization.DataTable();
data1.addColumn('string','Topping');
data1.addColumn('number','Slices');
for(var i=0;i<result.length;i++)
{
var r=result[i];
data1.addRow([r.Name,r.Inbound_Orders__c]);
}
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
var chart1= new google.visualization.AreaChart(document.getElementById('chart_hh'));
chart.draw(data, options);
chart1.draw(data1,options); }, {escape:true});
MyJSController.getObject_name(function(event,result){
alert('Hello'+result);
document.getElementById('dddd').innerHTML=String.ValueOf(result); },{escape:true});
}
</script>
<div id="chart_div" ></div>
<div id="chart_hh"></div>
<div id="dddd">Helloojjfs</div>
</apex:page>
When I call MyJSController.getObject_name in script tag (4th last line in script tag) in result I am getting [Object Object]. But I need String Order which I initialize in the constructor. Can you please tell me where I am wrong and to rectify this mistake?
I believe the issue is that your argument names are backwards. It should be:
MyJSController.getObject_name(function(result, event)
So the alert you are getting of an object is actually the event object.

Trying to call a webservice in my app but is is not found

I am trying to call a webservice. The webservice and calling code are all in the same project. When the javascript function tries to call the webservice function AttnCcc.saveAttnCcc, I get error : Microsoft JScript runtime error: 'AttnCcc' is undefined
The following code is in the aspx file which calls the service:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AttnCcc.asmx.cs" />
</Services>
</asp:ScriptManager>
In the same aspx file, I am trying to call it from the following js function:
<script type="text/javascript">
function ConfirmCcc(ID, webDataGridName) {
AttnCcc.saveAttnCcc("44,duplicate,this test data");
}
</script>
THe webservice is the the following asmx.cs file:
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace are
{
/// <summary>
/// Summary description for AttnCcc
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AttnCcc : System.Web.Services.WebService
{
[ScriptMethod]
[WebMethod]
public void saveAttnCcc(string ccc)
{
string cblCccText, tbCccText;
int Id;
string[] arr = ccc.Split(',');
Id = int.Parse(arr[0]);
cblCccText = arr[1]; tbCccText = arr[2];
}
}
What am I doing wrong?
You can't call a webservice of type void.
I changed to to return an int I never use and the calling js was able to find it.
public int saveAttnCcc(string ccc) {
...
return dummyInt;
}

Categories