enter image description hereI am new to Api stuff. I want to achieve following which I did. But I want to show list of places without using google UI. And from the list, clicked address should be in the form. How can I do that? Is there any example code that I can use, would be great.
Google place autocomplete
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key='******************'&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var latitude = place.geometry.location.A;
var longitude = place.geometry.location.F;
var mesg = "Address: " + address;
mesg += "\nLatitude: " + latitude;
mesg += "\nLongitude: " + longitude;
alert(mesg);
});
});
</script>
<span>Location:</span>
<input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />
Related
I'm trying to save latitude and longitude by autocomplete Google Maps, but I can't make this work. I don't know how to use Google Maps Api. I need to add 2 fields with longitude and latitude, and when I select my address from my input, these 2 fields ( longitude and latitude ) should be filled with the correct values.
What I have tried so far:
Google map api get Latitude and longitude from autocomplete without map
Here is my script
<script>
// This sample uses the Autocomplete widget to help the user select a
// place, then it retrieves the address components associated with that
// place, and then it populates the form fields with those details.
// This sample requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {types: ['geocode']});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component']);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places&callback=initAutocomplete"
async defer></script>
Here is my view
<div class="form-group col-md-4" style="left: 10px;position: relative" id="locationField">
<label class="label" for="jobs">
Address
</label>
<div class="input-group">
<div class="input-group-addon" style="border-color: #bbb">
<i class="icon-hotel-restaurant-235 u-line-icon-pro"></i>
</div>
<label class="input" style="height: 28px">
<input id="autocomplete"
placeholder="Enter your address"
onFocus="geolocate()"
type="text"
style="height: 33px"
name="address"/> </label>
</div>
</div>
I have written this script for one of my recent project this works fine for me
<script>
var autocomplete;
function initAutocomplete(){
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete-input'), {types: ['geocode']});
autocomplete.addListener('place_changed', getAddressDetails);
}
function getAddressDetails(){
var place = autocomplete.getPlace();
window.lat = place.geometry.location.lat();
window.long = place.geometry.location.lng();
}
function geolocate(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
This will be your input
<div id="autocomplete-container">
<input id="autocomplete-input" type="text"
class="autocomplete" autocomplete="off" spellcheck="false" dir="auto"
placeholder="Location" onFocus="geolocate()">
</div>
This code works fine for my projects
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
var placeId = place.place_id;
// to set city name, using the locality param
var componentForm = {
locality: 'short_name',
};
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById("city").value = val;
}
}
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lng;
document.getElementById("location_id").value = placeId;
});
I want to get the longitude and latitude using javascript, and than to compare it with the previous location. Something like Facebook does when you log in from another computer, but much more simplified. In order to achieve this I have created 2 hidden fields and when the user submits the form the values are to be sent to the server.
<body>
<p id="log">Login to continue:
<form action="welcome.php" method="post">
Username: <input type="text" name="user" required >
Password: <input type="password" required>
<input type="hidden" name= "longitude" id="longitude">
<input type= "hidden" name ="latitude" id="latitude">
<input type="submit" name="submit" onclick="getLocation()">
</p>
<script>
var x=document.getElementById("log");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementByID("longitude").value = longitude;
document.getElementByID("latitude").value = latitude;
}
</script>
But in welcome.php the code :
$latitude=$_POST["latitude"];
$longtude=$_POST["longitude"];
returns :
Notice: Undefined index: latitude in C:\xampp\htdocs\welcome.php on line 8
Notice: Undefined index: longitude in C:\xampp\htdocs\welcome.php on line 9
Is there better way to do this, and how to fix this?
You are trying to access the elements by ID, but they have no ID.
Either add an ID attribute to them, or reference them in a different way.
you have made mistake on document.getElementByID the d should be small ie document.getElementById
Change this
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementByID("longitude").value = longitude;
document.getElementByID("latitude").value = latitude;
}
to this
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById("longitude").value = longitude;
document.getElementById("latitude").value = latitude;
}
And it should work
Open firebug, click on label network and take a look into the post request if parameters langitude and longitude have been sent. If yes, the failure must be in your php script. If you cant't find both parameters, check your client code.
I want to render route on google map by lat long from previous page(send by html form)
and put the recieve value on php hidden type then pull value by jquery and define a start,end point
from value in hidden type finally call routefunction but it's not show the way route
I try to put alert in render section it's work fine but not show way route.I don't know why
This is my code
<?php
//get lat long from previous page html form
$press = $_POST["send"];
$lat1 = $_POST["lat1"];
$long1 = $_POST["long1"];
$lat2 = $_POST["lat2"];
$long2 = $_POST["long2"];
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my_key&sensor=false"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var rendererOptions = {draggable: true}; //define dragble direction
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var center = new google.maps.LatLng(13.76493,100.5383);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); //render map
calcRoute(); //call route function
}
function calcRoute()
{//get lat long from hidden type
$(document).ready(function(){
var lat1 = $("#lat1").val();
var long1 = $("#long1").val();
var lat2 = $("#lat2").val();
var long2 = $("#long2").val();
var start = new google.maps.LatLng(lat1,long1);//define start point
var end = new google.maps.LatLng(lat2,long2);//define end point
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
alert("DO"); //it's show alert when redirect from previous page
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
<?php
//put value from previous page on hidden type
echo "<input type='hidden' id='lat1' value='$lat1'>";
echo "<input type='hidden' id='long1' value='$long1'>";
echo "<input type='hidden' id='lat2' value='$lat2'>";
echo "<input type='hidden' id='long2' value='$long2'>";
?>
I have google map on my site(php,apache,mysql).
here is code:
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var point = new GLatLng(<? $default_ll ?>,<? $default_spn ?>);
map.setCenter(point, 15);
map.setUIToDefault();
map.setMapType(G_NORMAL_MAP);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
window.onload = initialize;
window.onunload = GUnload;
</script>
<div id="map_canvas" style="width:500px;height:300px;"></div>
I want to make button(outside of map div), so when user chose hes coords and clicks this button. Current location he is watching rightnow will be put in to database. Well for simplicity can you show how to assign current: ll to $new_ll and spn to $new_spn
The GMap2 map object has these methods:
var center = map.getCenter(); // returns GLatLng of center point of map
var span = map.getBounds(); // returns GLatLngBounds of current map view
Using these simply you could have a button like this:
<input type="button" onclick="javascript:alert(map.getCenter())" value="Show Coordinates"/>
More realistically, you'll define a function to be called by the button's onclick:
function showCenterAndSpan()
{
var center = map.getCenter();
var span = map.getBounds();
var ne = span.getNorthEast();
var sw = span.getSouthWest();
var coordStr = "lat=" + center.lat() + "&lng=" + center.lng() +
"&n=" + ne.lat() + "&e=" + ne.lng() + "&s=" + sw.lat() + "&w=" + sw.lng();
alert(coordStr); // Or, post this string to the server to save into the database
}
I'm trying to replicate the following exemple :
http://www.leigeber.com/2008/04/map-your-users-using-the-google-maps-api-and-php/
How to integrate this PHP source code with the following Java script (replacing lat/lgt with $latitude/$longitude above ??? Looks easy but I'm a bit lost in mixing PHP and Javascript together ! ;-(
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= 50.62829913465776;
var lgt= 4.650295972824097;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
// add a marker
map.openInfoWindow(map.getCenter(), document.createTextNode ("Center of the map at (lat - lgt)= ("+lat+" - "+lgt+") ! "));
// Large Map Default UI
map.setUIToDefault();
// Map type
map.setMapType(G_PHYSICAL_MAP);
}
}
</script>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1000px; height: 600px"></div>
</body>
Thanks in advance for your help.
Hub
ps: is this the best way to do it ? is it good to use hostip.info or should I use another one ??
Should be fairly easy. Once you've fetched the $latitude and $longitude according to the linked example, you can use PHP to echo those values out to your Javascript code.
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= <?php echo $latitude ?>;
var lgt= <?php echo $longitude ?>;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
.........
...............
</script>
That should get you going for the script mixing part. Remember, you've to use PHP to fetch the lat/long BEFORE you attempt to output the values to your JS.
In response to your queries, here's the general flow of code (say, in the file index.php):
<?php
// Code from the blog
$ip = $_SERVER['REMOTE_ADDR'];
.....
.......
$latitude = $res[2];
$longitude = $res[3];
?>
<html>
<head>
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= <?php echo $latitude ?>;
var lgt= <?php echo $longitude ?>;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
.........
...............
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
......
</body>
</html>
See if this helps you :)
Cheers,
m^e
According to this post http://www.techsirius.com/2014/07/visitor-realtime-geo-location-in-google-map.html it seems it is possible.
Basically it is fetching database record for country, state, and city based on given IP. It seems that database IP record is stored in IPlong format that is why it is possible to store that much IP record in one database.
After that all depended on Google Geocoding API and Google Maps JS v3 API.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&key=<?=$google_api_key?>"></script>
<script type="text/javascript">
$(document).ready(function(){
var option = {
center: new google.maps.LatLng(<?=$lat?>, <?=$lng?>),
zoom: 5
};
var map = new google.maps.Map(document.getElementById("visitor_map"), option);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?=$lat?>, <?=$lng?>),
map: map
});
});
</script>