Rewrite part of javascript with C#

457 views Asked by At

I'm writing this program in C# which should display Google Maps. I'm using the Google Maps JavaScript API which is the best one I could find. With the program you should be able to search for places.

The code:

window.onload = function() {

    var latlng = new google.maps.LatLng(52.785804, 6.897585);
    var options = {
        zoom: 15,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), options);
}
html, body {
    margin: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

#map {
    width: 80%;
    height: 100%;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
    <title>Google Maps</title>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

</head>

<body>
    <div id="map">
    </div>
</body>

</html>

Am I in some way able to edit the latlng using C#? Or does someone know an alternative way to use the Google Maps API with C#?

2

There are 2 answers

0
Ahsan On BEST ANSWER

If you are not using MVC or other server side technologies on this specific page your only option would be to load the lat/long from an AJAX call.

$.ajax({
    url: "url/to/your/api/that/returns/lat/long",
    success: function(result) {
        // process your JSON result and set the lat/long
    }
});

the API can be written on the server side using any language (including c#)

0
Graffito On

To display Google map in a Desktop application, e.g. Winforms, you may use a WebBrowser control and an HTML page (local file or embedded as resource).

It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.

Javascript to C#

-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }

-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />

C# to Javascript

-------C# code--------------------
object [] MyArgs = { "Hello" } ;   WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;

-------Javascript----------------
function MyJsFunction(s)  { alert(s) ; }