0

Is it possible to pass a value from a C# method to JavaScript as a parameter?

Google Maps JavaScript API wants to pass in hardcoded latitude and longitude. Is it possible to replace the lat and lng with a variable from a C# method?

var usermap = new google.maps.Map(document.getElementById('direction-map'), {
     zoom: 6,
     // User's lat and lng
     center: { lat: -24.345, lng: 134.46 }  // Australia.
});

I have the following method on a controller that grabs the lat and lng from a table. I'm concatenating in the example, but that's not important right now.

public async Task GetLatLongGeo(Observer observer) // Pass entire Observer record as a parameter
        {
        string address = (observer.StreetAddress); *// Get StreetAddress property from user's record*
        var Geokey = APIKey.GoogleGeocodekey; // Grab Google API key for Geocoding
        string url = $"https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={Geokey}";
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);
        string jsonresult = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
                GeoCodeObject geoInfo = JsonConvert.DeserializeObject<GeoCodeObject>(jsonresult);
                var userLatitude = geoInfo.results[0].geometry.location.lat.ToString(); // Pulls lat
                var userLongitude = geoInfo.results[0].geometry.location.lng.ToString(); // Pulls lng
                StringBuilder latLongString = new StringBuilder();
                latLongString.Append(userLatitude + "," + userLongitude);
                string fullLatLong = latLongString.ToString();
                observer.LatLng = fullLatLong;
            }
        }

The next step would be to take those lat and lng values, and replace the hardcoded lat and lng on the Google MapsAPI example.

Is this even possible? I've tried the solution from here, google maps API for C#, but no luck. Fails on the WebResponse response = request.GetResponse(); step.}

I was also wondering if there was a way to convert a JSON value to a JS variable? That could help my issue as well.

I've also tried the AJAX call, but I'm so confused by it, and I don't think there's a great way to step through it. Similar Ex:

$.ajax({  
        url: 'EmployeeService.asmx/AddEmployee',  
        method: 'post',  
        data:   '{emp: ' + JSON.stringify(employee) + '}',  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        success: function () {  
            getAllEmployees();  
            console.log(data);  
        },  
        error: function (err) {  
            console.log(err);  
        }  
    });

UPDATE:

My JSON info looks like this:

{
   "results": [
      {
         "address_components": [
            {
               "long_name": "313",
               "short_name": "313",
               "types": [
                  "street_number"
               ]
            },
            {
               "long_name": "North Plankinton Avenue",
               "short_name": "N Plankinton Ave",
               "types": [
                  "route"
               ]
            },
            {
               "long_name": "Menomonee Valley",
               "short_name": "Menomonee Valley",
               "types": [
                  "neighborhood",
                  "political"
               ]
            },
            {
               "long_name": "Milwaukee",
               "short_name": "Milwaukee",
               "types": [
                  "locality",
                  "political"
               ]
            },
            {
               "long_name": "Milwaukee County",
               "short_name": "Milwaukee County",
               "types": [
                  "administrative_area_level_2",
                  "political"
               ]
            },
            {
               "long_name": "Wisconsin",
               "short_name": "WI",
               "types": [
                  "administrative_area_level_1",
                  "political"
               ]
            },
            {
               "long_name": "United States",
               "short_name": "US",
               "types": [
                  "country",
                  "political"
               ]
            },
            {
               "long_name": "53203",
               "short_name": "53203",
               "types": [
                  "postal_code"
               ]
            }
         ],
         "formatted_address": "313 N Plankinton Ave, Milwaukee, WI 53203, USA",
         "geometry": {
            "location": {
               "lat": 43.0341871,
               "lng": -87.9119293
            },
            "location_type": "ROOFTOP",
            "viewport": {
               "northeast": {
                  "lat": 43.03553608029149,
                  "lng": -87.9105803197085
               },
               "southwest": {
                  "lat": 43.0328381197085,
                  "lng": -87.91327828029151
               }
            }
         },
         "place_id": "ChIJp3lqJaIZBYgRNWrX62hk4GU",
         "plus_code": {
            "compound_code": "23MQ+M6 Milwaukee, Wisconsin, United States",
            "global_code": "86MJ23MQ+M6"
         },
         "types": [
            "street_address"
         ]
      }
   ],
   "status": "OK"
}

So I would be getting the longitude and latitude with:

geoInfo.results[0].geometry.location.lat.ToString();

geoInfo.results[0].geometry.location.lng.ToString();

Mitchell
  • 111
  • 15
  • I can't see what your AddEmployee function is doing but what you're asking is possible. What are you exactly returning from AddEmployee? Your `success` callback doesn't have a parameter to see its output. – johnmikelridzz Dec 14 '19 at 19:46
  • I'm working locally, so the url would be more like: ``` url: https://localhost:44388/Observers/Details/'+UserId, ``` That was just an example. To be honest, I'm not sure what that AJAX is doing. – Mitchell Dec 14 '19 at 20:00
  • And I believe I would be running the method in the success: CallGoogleMapsJS(observer); The CallGoogleMapsJS() method with the entire observer record – Mitchell Dec 14 '19 at 20:18
  • Considering your json result, you can just access the lat lng by results.geometry.location.lat and results.geometry.location.lng :) – johnmikelridzz Dec 14 '19 at 20:38
  • But how would that look when calling it through Google Maps JS? var usermap = new google.maps.Map(document.getElementById('direction-map'), { zoom: 6, // User's lat and lng center: { lat: results.geometry.location.lat, lng: results.geometry.location.lng } }); – Mitchell Dec 14 '19 at 20:43
  • Create a var, say call it result, at the top most of your tags and in your success function, make the result variable take the data from the success function. It should work afterwards. – johnmikelridzz Dec 14 '19 at 20:48
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204268/discussion-between-mitchell-and-johnmikelridzz). – Mitchell Dec 14 '19 at 21:10

0 Answers0