Calling a javascript function using an ASP.Net button control - javascript

Here is my code:
<script type="text/javascript">
var geocoder;
var map;
var latlngstr;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlngstr = results[0].geometry.location;
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
document.getElementById('lat').value = latlngstr.lat();
document.getElementById('lng').value = latlngstr.lng();
}
</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div>
<input id="address" type="text" value="sydney" />
<input type="button" value="Geocode" onclick="codeAddress()">
<input id="lat" type="text" />
<input id="lng" type="text" />
</div>
<asp:Button ID="Button1" runat="server"
Text="Button" EnableViewState="False"
ViewStateMode="Disabled" OnClientClick="javascript:return codeAddress();"/>
<div id="map-canvas"></div>
</form>
</body>
</html>
I want to call the function codeAddress. When I call this function with an html button, the button with the value Geocode, it works fine. But when I call that function with an ASP.Net button the 'else' part is executed and it produces no result.

I infer that what you want to do is use the geocoding code to obtain the latitude and longitude and then post back with those.
Rather than make one button do client-side code and (at the same time) post back, I'd keep the HTML button but start a form post from your JavaScript code, once the fields have been set:
document.getElementById('lat').value = latlngstr.lat();
document.getElementById('lng').value = latlngstr.lng();
document.forms[0].submit();

Related

I am not able to pass values of lat and lng in vue js?

I am using vue js and I am able to pass username. But I am not able to pass lat and lng values. When checking, I am able to post username but lat and lng is coming as null.
My html code is
<form id="submitBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<div id="map"></div>
<input name="lat" type="text" id="lat" v-model="lat"><br>
<input name="lng" type="text" id="lng" v-model="lng">
<input name="username" type="text" class="form-control" id="name" placeholder="Name" required="required" v-model="username" data-parsley-minlength="4"/>
</form>
When Clicking on the map. I am able to load lat and lng values but I am not abe to pass
My script to load map values is
<script>
//map.js
//Set up some of our variables.
var map; //Will contain map object.
var marker = false; ////Has the user plotted their location marker?
//Function called to initialize / create the map.
//This is called when the page has loaded.
function initMap() {
//The center location of our map.
var centerOfMap = new google.maps.LatLng(52.357971, -6.516758);
//Map options.
var options = {
center: centerOfMap, //Set center.
zoom: 7 //The zoom value.
};
//Create the map object.
map = new google.maps.Map(document.getElementById('map'), options);
//Listen for any clicks on the map.
google.maps.event.addListener(map, 'click', function(event) {
//Get the location that the user clicked.
var clickedLocation = event.latLng;
//If the marker hasn't been added.
if(marker === false){
//Create the marker.
marker = new google.maps.Marker({
position: clickedLocation,
map: map,
draggable: true //make it draggable
});
//Listen for drag events!
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
//Marker has already been added, so just change its location.
marker.setPosition(clickedLocation);
}
//Get the marker's location.
markerLocation();
});
}
//This function will get the marker's current location and then add the lat/long
//values to our textfields so that we can save the location.
function markerLocation(){
//Get location.
var currentLocation = marker.getPosition();
//Add lat and lng values to a field that we can save.
document.getElementById('lat').value = currentLocation.lat(); //latitude
document.getElementById('lng').value = currentLocation.lng(); //longitude
}
//Load the map when the page has finished loading.
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
My vue js code is
<script>
submitBox = new Vue({
el: "#submitBox",
data: {
lat : '',
lng : '',
username: '',
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.lat;
data['lng'] = this.lng;
data['username'] = this.username;
$.ajax({
url: 'http://127.0.0.1:8000/api/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Success")
}
else {
vm.response = e;
alert("Failed")
}
}
});
return false;
}
},
});
</script>
I am able to get username. But I am gettting null values for lat and lng.
BUT WHEN I CLICK ON THE MAP I AM ABLE TO PRINT LAT AND LNG values but I am not able to pass the same. Can anybody please help me to solve the issue.
v-model isn't recognizing that the value attribute of your "lat" input field has been programmatically changed. Instead, you can do something like this:
<input name="lat" type="text" id="lat" ref="myLatField" v-model="lat">
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.$refs.myLatField.value;
...

Proper use of ng-submit

I have a form that submits a location to Google's Geocoder and returns the lat/long and changes the map. If I use ng-click on the icon it doesn't work unless I click on it twice. If I use ng-submit on the form it appends to the url and doesn't perform the task. I feel like I'm close to getting this to work but I'm lost as to what I'm doing wrong.
Below is the form
<li>
<form action="" class="search-form" ng-submit="convertLatLonToAddress()">
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
<i class="fa fa-search form-control-indicator"></i>
</div>
</form>
</li>
And here is the function
$scope.convertLatLonToAddress = function(){
var address = $('#search').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
}
});
};
Thanks to #PSL it's fixed! See below:
<li>
<form class="search-form" ng-submit="convertLatLonToAddress(searchText)">
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">
<button style="visibility: hidden"></button>
<a ng-click="convertLatLonToAddress(searchText)">
<i class="fa fa-search form-control-indicator"></i>
</a>
</div>
</form>
</li>
And
$scope.convertLatLonToAddress = function(searchText){
// var address = $('#search').val();
var address = searchText;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
$scope.$apply();
}
});
};
You need to invoke the digest cycle manually inside the async call of geocode, since geocode does not run inside angular context.
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
$scope.$apply();
}
});
Everytime you click, ng-click triggers the digest cycle so previous cycle runs the non angular async call and updated scope which angular is unaware, when you click on it again it runs the digest cycle again and does the same but that time the values you set previously will be picked and that is why it takes 2 clicks. For ng-submit to execute you need a form element trigger, ex: a button or input type="submit" that causes submit behavior to happen on the form. You should also remove action from form unless you really intend to do a redirection.
Apart from that you can use ng-model on the textbox and pass the value to your function as well instead of getting value from DOM directly.
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">
and pass the value via ng-click as ng-click="convertLatLonToAddress(searchText)" and use it inside your function.
In order to avoid scope.apply(); in your controller you could abstract out geoCoder to an angular service and return a promise (creating deferred object) and use that service in your controller.
myApp.service('geoCoderService', ['$q', function($q){
this.getCoordinates = function(address){
var defer = $q.defer();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
return defer.resolve({latitude :latitude , longitude :longitude });
}
//faliure
defer.reject(status);
});
return defer.promise;
}
});
inject geoCoderService and get data using:
geoCoderService.getCoordinates(address).then(function(coordinates){
//populate it
}).catch(function(errorStatus){ /*ooops Error*/ })
Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.convertLatLonToAddress = function() {
var address = $('#search').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.lat = results[0].geometry.location.lat();
$scope.lon = results[0].geometry.location.lng();
console.log($scope.lat + ' and ' + $scope.lon);
setTimeout(function(){$scope.$apply();},0)
}
});
};
});
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<li>
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
<i class="fa fa-search form-control-indicator"></i>
<button ng-click="convertLatLonToAddress()">Click</button>
<br>
Lat : <input type="text" ng-model="lat"><br>
Lon : <input type="text" ng-model="lon">
</div>
</li>
</div>
</body>

Using variables for longitude and latitude with google maps api

I've just started using the google maps API for browsers but I can't seem to get it to work when I place variables in the longitude/latitude places instead of numbers directly.
I need the maps to populate from the value of two input elements.
It doesn't work with variables but if you change the variables in the function to numbers it works perfectly.
Yes I'm aware I shouldn't post my API key but this is one I use on an off account for testing and I will end up deleting it.
function initialize() {
var userLng = $('#lng').val();
var userLat = $('#lat').val();
var mapOptions = {
center: { lat: userLat, lng: userLng },
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
height: 30em;
width: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script>
<form>
<input type="text" id="lng" name="lng" value="30">
<input type="text" id="lat" name="lat" value="40">
</form>
<div id="map-canvas"></div>
You are using strings, please try with floats:
var userLng = parseFloat($('#lng').val());
var userLat = parseFloat($('#lat').val());
var mapOptions = {
center: { lat: userLat, lng: userLng },
zoom: 8
};
You shuld parseFloat() your input values, you need numbers not string.
function initialize() {
var userLng = parseFloat($('#lng').val());
var userLat = parseFloat($('#lat').val());
var mapOptions = {
center: { lat: userLat, lng: userLng },
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
height: 30em;
width: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script>
<form>
<input type="text" id="lng" name="lng" value="30">
<input type="text" id="lat" name="lat" value="40">
</form>
<div id="map-canvas"></div>
Edit, sr parseFloat not parseInt

Is Google api limit based on ip or page ? client side scripting avoid limit crossing?

In my server i am using some function to find out pickup and drop lat and lang , direction from google map api services,so limit is crossed some days so i have desiede to go with user side scripting to calculate all google api service using following code this will help me ?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body onload="geolocate1()">
<input type="text" id="pickup" onFocus="geolocate()" placeholder="Enter your pick up place" />
<input type="text" id="plat" value="" id="plat"/>
<input type="text" id="plang" value="" id="plang"/>
<input type="text" id="pstatuslat" value="error" />
<input type="text" id="km" />
</br>
</br>
<input type="text" id="drop" onFocus="geolocate1()" placeholder="Enter your Drop off place"/>
<input type="text" id="dlat" value="" id="plat"/>
<input type="text" id="dlang" value="" id="plang"/>
<input type="text" id="dstatuslat" value="error" />
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<input type="button" onclick="GetLocation1();GetLocation();calcRoute();" value="Book Now" />
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
<!--
function GetLocation() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("pickup").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.getElementById('plang').value= longitude;
document.getElementById('plat').value= latitude;
document.getElementById('pstatuslat').value= "ok";
} else {
document.getElementById('pstatuslat').value= "error";
}
});
};
function GetLocation1() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("drop").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.getElementById('dlang').value= longitude;
document.getElementById('dlat').value= latitude;
document.getElementById('dstatuslat').value= "ok";
} else {
document.getElementById('dstatuslat').value= "error";
}
});
};
//-->
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var autocomplete;
function geolocate1() {
// Create the autocomplete object, restricting the search
var input = document.getElementById('pickup');
var options = {types: ["geocode"],componentRestrictions: {country: 'uk'}};
autocomplete = new google.maps.places.Autocomplete(input, options);
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
function geolocate() {
// Create the autocomplete object, restricting the search
// to geographical location types.
var input = document.getElementById('drop');
var options = {types: ["geocode"],componentRestrictions: {country: 'uk'}};
autocomplete = new google.maps.places.Autocomplete(input, options);
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
var directionsService = new google.maps.DirectionsService();
function calcRoute() {
var start = document.getElementById('pickup').value;
var end = document.getElementById('drop').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var km = parseFloat(route.legs[0].distance.text.replace(" km", ""));
document.getElementById('km').value = km * 0.6214;
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
Google API is limited with your Key using. Doesnt matter, if you have the same IP or different, each call to the Google API with you registered Key will be counted.
F.e. using Google Elevation API is limited for 2500 calls each day, doesnt matter, who is calling this, its limited to you API Key.

How to pass Latitude Longitude from HTML form to Google Maps

I want to pass latitude and longitude from user. How I can pass parameters from html form to google map API?
How to learn complete google map API step by step which start to end.
and how to add more then one lat and lng to one map?
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
var lat=51.508742;
var lng=8.120850;
var myCenter=new google.maps.LatLng(lat,lng);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<form id="form1">
<table>
<tr>
<td>Enter Latitude:</td>
<td>
<input type="text" name="lat" value="13.053147716796578" />
</td>
</tr>
<tr>
<td>Enter Longitude:</td>
<td>
<input type="text" name="lng" value="80.2501953125" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" />
</td>
</tr>
</table>
<div id="googleMap" style="width:500px;height:380px;"></div>
</form>
</body>
</html>
Use a google.maps.event.addDomListener to listen to the form submit event.
Give your lat and lng input fields an ID so that you can identify them.
Create a marker from the form values (and/or center the map on the location).
You also want to validate the user input. You should check that the user entered numbers and that they are valid lat and lng values.
More information here on how to validate the latitude value on a mercator projection.
Here is a complete and working example to achieve what you want:
HTML
<form id="mapCenterForm">
Lat: <input type="text" id="lat" />
<br />
Lng: <input type="text" id="lng" />
<br />
<input type="submit" value="Center map" />
</form>
<br />
<div id="map-canvas"></div>
JavaScript
// Calculate maximum latitude value on mercator projection
var maxLat = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// DOM event listener for the center map form submit
google.maps.event.addDomListener(document.getElementById('mapCenterForm'), 'submit', function(e) {
e.preventDefault();
// Get lat and lng values from input fields
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
// Validate user input as numbers
lat = (!isNumber(lat) ? 0 : lat);
lng = (!isNumber(lng) ? 0 : lng);
// Validate user input as valid lat/lng values
lat = latRange(lat);
lng = lngRange(lng);
// Replace input values
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
// Create LatLng object
var mapCenter = new google.maps.LatLng(lat, lng);
new google.maps.Marker({
position: mapCenter,
title: 'Marker title',
map: map
});
// Center map
map.setCenter(mapCenter);
});
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function latRange(n) {
return Math.min(Math.max(parseInt(n), -maxLat), maxLat);
}
function lngRange(n) {
return Math.min(Math.max(parseInt(n), -180), 180);
}
initialize();
Demo
JSFiddle demo
Give the elements IDs, like:
<input type="text" id="lat" name="lat" value="13.053147716796578" />
Just use Javascript to get the values:
var lat=document.getElementById('lat').value;
var lng=document.getElementById('lng').value;

Categories