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;
});
Related
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" />
How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>
In my web app, I give the user the ability to go back and edit the information that they entered. However, for some reason when they resubmit, the locations latitude/longitude does not recalculate. This happens when they don't change the job location. Is there a way to make google maps find that job location without any user interference?
My code is below:
var jobLocationChanged = false;
var jobLocationpickChanged = false;
function initialize() {
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.348565,-122.263069),
new google.maps.LatLng(37.496039,-122.062912));
var options = {
bounds: defaultBounds,
componentRestrictions: {country: 'us'}
};
var input = document.getElementById('jobLocation');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
$('#jobLocation-lat').val(place.geometry.location.lat());
$('#jobLocation-lng').val(place.geometry.location.lng());
//$('#jobLocation-pos-label').text('Lat : '+place.geometry.location.lat()+', Lng : '+place.geometry.location.lng());
jobLocationChanged = false;
});
var input2 = document.getElementById('jobLocationpick');
var autocomplete2 = new google.maps.places.Autocomplete(input2, options);
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
var place = autocomplete2.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
$('#jobLocationpick-lat').val(place.geometry.location.lat());
$('#jobLocationpick-lng').val(place.geometry.location.lng());
//$('#jobLocationpick-pos-label').text('Lat : '+place.geometry.location.lat()+', Lng : '+place.geometry.location.lng());
jobLocationpickChanged = false;
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I would really appreciate any help! Thanks
You may request the predictions for the given string via the Autocomplete-Service
Actually I working on a website where user can add his business. And I want to give him a functionality to add any location on a map. As he saves his business details along with that map details should go to database so that after posting his business on website it should show that location on a map. In short, I want to allow the user to add his location on a map and on a website for that specific user map should show his location on a map.
As I am new to all this I am getting confused how to do this. So please help me out. I searched for it on google but I am not getting any help for my problem.
Thanks in advance....
Here is my tried code:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
#media print {
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
}
</style>
</head>
<body>
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.map.php
* Type: map
* Name: Map
* Purpose: Accept the keyword & find it on a map.
* -------------------------------------------------------------
*/
function smarty_function_map($params, &$smarty)
{
?>
<div id="panel">
<label>Location/Area*</label><input id="searchTextField" type="text" size="50" placeholder="Enter Location/Area">
<input type="text" id="city2" name="city2" />
<input type="text" id="cityLat" name="cityLat" />
<input type="text" id="cityLng" name="cityLng" />
</div>
<div id="map-canvas"></div>
<?php
}
?>
</body>
</html>
To allow users to add a marker to the map by clicking on it, you'll need to setup an event listener that will listen for any clicks on the map. Example:
var marker;
google.maps.event.addListener(map, 'click', function(event) {
if ( marker ) {
marker.setPosition(event.latLng);
} else {
marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true
});
}
});
You'll also want to enable the user to drag the marker after they've plotted it. You can do this by setting the marker to draggable (I did this in the above example). You'll also need to listen for any changes by attaching an event listener to the marker in question:
google.maps.event.addListener(marker, 'dragend', function(){
//Do something because marker has been dragged somewhere...
});
Finally, every time the map is clicked or a marker is dragged, you'll need to save the resulting latitude and longitude values in a hidden field(s) so that you can save the position in your database.
I am working in joomla 2.5 and I have to create a module for Google map and using Google map api v2.
and I am using geocoder = new GClientGeocoder(); but it is now working
output image:-
My html <div> tag
<div id="map_canvas" style="width: 800px; height:800px;"></div>
My script
<script>
//<![CDATA[
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
//calls map to appear inside <div> with id, "map_canvas"
map = new GMap2(document.getElementById("map_canvas"));
//adds zoom and arrow controls to map
geocoder = new GClientGeocoder();
map.setMapType(G_SATELLITE_MAP);
var allAddress = "Dubai~Abu Dhabi";
var addresses = new Array();
addresses = allAddress.split("~");
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
alert(_cur);
if (!point) {
alert(_cur + " not found");
} else {
alert(_cur+":"+point);
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
//]]>
</script>
See below code and try it.
I am using php static array you can connect your database and create array according your requirement. see the array below.
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
Below My Code Take a look.
<html>
<head>
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyDwFjOazEAe1MI7nHV6vUwkWytOp8LH2Zk" type="text/javascript"></script>
</head>
<body onload="initialize();">
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
<script>
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var addresses = ["<?php echo implode ('","', $item); ?>"]
var geocoder = new GClientGeocoder();
//var addresses = ["A II Z, Ibn Battuta Mall, Sheikh Zayed Road, 5th Interchange, Jebel Ali Village, Dubai","A. Testoni,Dubai Festival City Mall, Ground Floor, Dubai", "Abdulla Hussain Khunji, The Dubai Mall,Downtown, Abu Dhabi"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
//alert(_cur + " not found");
//map.setCenter(new GLatLng(0, 0), 6);
//map.setUIToDefault();
} else {
//console.log(_cur+":"+point);
//alert(_cur);
var cafeIcon = new GIcon(G_DEFAULT_ICON);
// Set up our GMarkerOptions object
markerOptions = { icon:cafeIcon };
map.setCenter(point, 6);
var marker = new GMarker(point, markerOptions);
map.addOverlay(marker);
var sales = new Array();
sales = _cur.split("|");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address <br /><span class='para1' style='font-weight:normal;'>" + sales[1] + "</span></p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
</script>
<div id="map_canvas" style="width:100%; height:750px;"></div>
</body>
</html>