How to get the latitude and longitude in this code - google-maps

Here i am using google map API ,user search their area means i want to get the latitude and logidute and stored in my database, i don't know how to do ,i am new in google map integrating please help me some one
// This sample uses the Place Autocomplete widget to allow the user to search
// for and select a place. The sample then displays an info window containing
// the place ID and other information about the place that the user has
// selected.
// This example 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=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
// Set the position of the marker using the place ID and location.
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location
});
marker.setVisible(true);
document.getElementById('place-name').textContent = place.name;
document.getElementById('place-id').textContent = place.place_id;
document.getElementById('place-address').textContent =
place.formatted_address;
infowindow.setContent(document.getElementById('infowindow-content'));
infowindow.open(map, marker);
});
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCW8mAAfcRRb4hrB33AWG_Mk71ZtORjOAo&libraries=places&callback=initMap"
async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>

As described in the documentation you can use the Google Maps Geocoding API and query using an address and the api will respond with the geocoding (including latitude and longitude) for that address. For example the following request,
curl "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY"
, will repsond with
{
...
"geometry" : {
"location" : {
"lat" : 37.4223664,
"lng" : -122.084406
},
...
},
...
}
You can find a detailed example here.

Related

Google Map add marker from two text boxes values (lat & lng)

I have an app where the user clicks on the map to create a marker and store it in the database.
This code under my question works fine, but now I would like to add a function to display a marker from lat and lng values ​​contained in two text boxes (camera_lat and camera_long) imported from the database.
Does anyone know how to do that ?
let map;
var marker;
function initmap() {
var latlng = new google.maps.LatLng(43.920340, 7.1325917);
var myOptions = {
zoom: 9,
center: latlng,
gestureHandling: 'greedy'
};
map = new google.maps.Map(document.getElementById("div_map"), myOptions);
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
clickLat = event.latLng.lat();
clickLon = event.latLng.lng();
// show in input box
document.getElementById("camera_lat").value = clickLat.toFixed(5);
document.getElementById("camera_long").value = clickLon.toFixed(5);
// if marker exist remove it show only one marker
if(marker != null){
marker.setMap(null);
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(clickLat,clickLon),
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initmap);
Take the values from the input fields, use them to make a google.maps.LatLng object, use that to position the marker.
make a function to add the marker:
function addMarker(latLng, map) {
// if marker exist remove it show only one marker
if (marker != null) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map
});
}
if you want to add the marker on page load (and have data in the input fields at that time, call the function after instantiating the map:
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
then use that in the existing code and in a click listener function on a button to add the marker:
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
});
proof of concept fiddle
code snippet:
let map;
var marker;
function initmap() {
var latlng = new google.maps.LatLng(43.920340, 7.1325917);
var myOptions = {
zoom: 9,
center: latlng,
gestureHandling: 'greedy'
};
map = new google.maps.Map(document.getElementById("div_map"), myOptions);
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
clickLat = event.latLng.lat();
clickLon = event.latLng.lng();
// show in input box
document.getElementById("camera_lat").value = clickLat.toFixed(5);
document.getElementById("camera_long").value = clickLon.toFixed(5);
addMarker(event.latLng, map);
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
});
}
function addMarker(latLng, map) {
// if marker exist remove it show only one marker
if (marker != null) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initmap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#div_map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="camera_lat" value="43.661" />
<input id="camera_long" value="6.90188" />
<input id="btn" value="add marker" type="button" />
<div id="div_map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
</body>
</html>

Google map preview selected location on map

I would like to allow my user to pick a location as well as previewing searched location to pick location.
Problem
Am not able to integrate the search-box to preview the searched location.
Code I am using
<input type="text" id="search">
<div id="map"></div>
var map = document.getElementById('map');
var lp = new locationPicker(map, {
setCurrentPosition: true,
lat: -13.9867852,
lng: 33.77027889
}, {
zoom: 15 // You can set any google map options here, zoom defaults to 15
});
// Listen to button onclick event
confirmBtn.onclick = function () {
var location = lp.getMarkerPosition();
var location = location.lat + ',' + location.lng;
console.log(location);
};
google.maps.event.addListener(lp.map, 'idle', function (event) {
var location = lp.getMarkerPosition();
var location = location.lat + ',' + location.lng;
console.log(location);
});
How do i enable the input to search location and display it on the map
Edit, Have managed to enable search on the input but can't move the marker to the selected location
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var input = document.getElementById('search');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions({'country':['mw']});
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
/*
console.log(place.geometry['location'].lat());
console.log(place.geometry['location'].lng());
console.log(place.name);
console.log(place.formatted_address);
console.log(place.vicinity);
console.log(place.url);
console.log(place.address_components);*/
if(!place.geometry) {
return;
}
console.log(place);
});
}
Kindly check out this sample fiddle that have a search box and a map. When a user selects a place suggestion in the autocomplete input, the sample then calls the getPlace() method, and then it opens an info window to display place details.
You can create an infowindow to display some place details:
<input id="search" type="text" placeholder="Enter a location">
<div id="map"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initialize" async defer></script>
</body>
In the initialize() function, declare your infowindow and marker objects and then set the marker position and infowindow content in the place_changed listener which is called whenever the user selects an autocomplete address suggestion.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -13.9867852, lng: 33.77027889},
zoom: 15
});
var input = document.getElementById('search');
var autocomplete = new google.maps.places.Autocomplete(input);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
autocomplete.setComponentRestrictions({
'country': ['mw']
});
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
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.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(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
});
}
You can also check out this example from the public documentation.
Hope this helps!

How to get location coordinates knowing place_id via google javascript api

I know place_id, and I need to know it's coordinates.
I can do GET https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE
which gives me something like that:
``` "results" : [
{
"address_components" : [...],
"formatted_address" : "New York County, NY, USA",
"geometry" : {
"bounds" : {...},
"location" : {
"lat" : 40.7830603,
"lng" : -73.9712488
},
"location_type" : "APPROXIMATE",
"viewport" : {...}
},
"partial_match" : true,
"place_id" : "ChIJOwE7_GTtwokRFq0uOwLSE9g",
"types" : [...]
}
],
"status" : "OK"
```
but I need to do it via javascript api.
I don't have any maps on my page, just need to get the coordinates.
From the example in the Google Maps Javascript API v3 documentation (with your place_id):
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
map.fitBounds(place.geometry.viewport);
}
});
working fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var request = {
placeId: 'ChIJOwE7_GTtwokRFq0uOwLSE9g'
};
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
map.fitBounds(place.geometry.viewport);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
You don't need a map. It is a Restful web service that returns a JSON string. In your application, you only need to send a HTTP request to
GET https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE
and then parse the JSON string returned, and retrieve the latlng inside.
If you are using Jquery in your web app, you may do
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE",
dataType: "text",
success: function (yourJSONstring){
var respJson = $.parseJSON(yourJSONstring);
// then something like ...
// respJson.results[0].geometry.location.lat;
// respJson.results[0].geometry.location.lng;
},
error: function (xhr) {
}
});
it is happening because the location property is of type google.maps.LatLng.
For you to get the lat and lng the following functions can be used:
example:
place.geometry.location.any_function_below()
1. toString(): Converts to string representation.eg ((37.8042802, -122.41364429999999))
2. lat(): Returns the latitude in degrees.
3. lng(): Returns the longitude in degrees.
4. toJSON(): Converts to JSON representation ({lat: "", lng: ""}).
5. toUrlValue(precision?:number): Returns a string of the form "lat,lng" for this LatLng. We round the lat/lng values to 6 decimal places by default.
you can read more here: https://developers.google.com/maps/documentation/javascript/3.exp/reference#LatLng.
`//only add these line under function`
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);
var lng = place.geometry.location.lng();
var lat = place.geometry.location.lat();
var latlng = {lat , lng};
console.log(latlng);
});
You can retrieve it location like this
var obj = JSON.parse(yourJSONstring);
obj.results[0].geometry.location.lat;
obj.results[0].geometry.location.lng;

Google map API theme option page not displaying

I'm having some issues with the integration of a google map in my web site which can geocode an address before displaying the map with the correct location.
So i have a script (it worked when i was in localhost but since i put the web site online nothing happens) :
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
var firstLoc;
function findAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address' : document.getElementById('address_field').value},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map-location"),
{
center: firstLoc,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert('Geocode failed: ' + status);
}
}
);
}
google.maps.event.addDomListener(window, 'load', findAddress);
</script>
I put an address in a field in my theme option page then i register the value and put it in a hidden input in my front-end and try to get it with geocoder.geocode( { 'address' : document.getElementById('address_field').value}
Seems to have a problem with geocoding, i tested with a simple script with a fix position and it showed fine.
In case you need it this is how i display the map in the front-end :
<div class="contact-map">
<div id="map-location"></div>
<form class="address-hidden">
<?php echo "<input id='address_field' type='text' value= '{$content_options['geolocal_setting']}'/>"?>
</form>
</div>

Google Map - Convert v2 to v3 -drag icon and retrieve lat/long

I have an application that I wrote years ago in Google Map v2 that displayed a map from a given initial lat/long and placed an icon on the map. This webpage was a form with a text box for the lat and long. The page allowed the user to drag the icon to actual location of where a wildfire was located. The new lat/long was placed into the text box and the user could submit the form. I have not found a suitable replacement in v3 for this process. And now I get an error message that a new API key is required from Google Maps. But I also know that in May that v2 may no longer work. So I would like to update this app to v3. Any ideas of where I can find this? Here is an example of the old page http://nfsdata.unl.edu/wildfire/testmap.asp The page is writen in ASP. And we do not have access to PHP on this server. Thanks
That is a very straightforward application.
Your v2 code:
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var center = new GLatLng(41.33,-96.95);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(center, 13);
var marker = new GMarker(center, {draggable: false});
map.addOverlay(marker);
GEvent.addListener(map, "click", function(overlay, point) {
if (overlay) {
map.removeOverlay(overlay);
} else {
map.clearOverlays()
map.addOverlay(new GMarker(point));
document.getElementById("loclats").value = point.lat();
document.getElementById("loclongs").value = point.lng();
}
});
}
}
//]]>
</script>
Simple translation to v3 (not tested):
<script type="text/javascript">
//<![CDATA[
function load() {
var center = new google.maps.LatLng(41.33,-96.95);
map = new google.maps.Map(document.getElementById("map"),{
center:center,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position:center
});
google.maps.event.addListener(marker, "click", function() {
marker.setMap(null);
});
google.maps.event.addListener(map, "click", function(evt) {
var point = evt.latLng;
marker.setPosition(point);
document.getElementById("loclats").value = point.lat();
document.getElementById("loclongs").value = point.lng();
});
}
}
//]]>
</script>
working example