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
Related
I need help with google places autocomplete API. I am getting the autocomplete address and lat and long from the API. Without restriction to a country the code works fine and I get the desired address, lat and long. However when I try to add country restriction, the lat and long fails to send along with my form.
Here is the working code without country restriction:
JS
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here is the code with country restriction that I need help with:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the lines that's causing the problem:
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
My form:
<html>
<head>
<title>Address Demo</title>
</head>
<body>
<form action="address.php" method="GET">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading" style="background-color:#00CDCD">
<h2 class="panel-title">Address</h2>
</div>
<div class="panel-body">
<input name="address" id="searchTextField" placeholder="Enter area name" type="text" class="form-control" required>
<input type="hidden" name="latii" id="latitude">
<input type="hidden" name="lngii" id="longitude">
<input type="submit" name="submit" value="SUBMIT" class="bookingbtn top-10 bottom-20">
</div>
</div>
</form>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</body>
</html>
address.php
<?php
$address = $_GET['address'];
$latii = $_GET['latii'];
$lngii = $_GET['lngii'];
echo "$address </br>";
echo "$latii </br>";
echo "$lngii";
?>
Thanks for your help in advance.
I finally got it to work. Thanks to the answer here How to limit google autocomplete results to City and Country only.
My working code is:
<script>
function initialize() {
var options = {
types: ['geocode'],
componentRestrictions: {country: "us"}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
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;
...
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.
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;
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();