Edit: I solved the problem. Leaving it up in case someone needs something similar in the future.
I am trying to use google map api to get coordinates and save the information in a database. If the user drags the marker then a form is updated with the information. User can also enter the information manually in the form if she wants and the map will be updated with a new marker. Then the user can click submit and the information will be saved in the database.
<form action="{{ route('YOUR_ROUTE') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<div style="padding-top: 10px;">
<div id="map-location"></div>
</div>
{{-- visibility, lat, lng, location --}}
<input class="form-control" type="text" name="location_name" id="location_name" placeholder="Location">
<input class="form-control" type="text" name="latitude" id="latitude" placeholder="Latitude" style="max-width: 50%;">
<input class="form-control" type="text" name="longitude" id="longitude" placeholder="Longitude" style="max-width: 50%;">
<button type="submit" class="btn btn-primary">Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</div>
</form>
<script>
//initialise and add the map
function initMap(){
// location of midtown manhattan
var midtown = {lat: 40.7549, lng: -73.9840};
// the maps centered at midtown
var map = new google.maps.Map(document.getElementById('map-location'),{zoom:17, center:midtown});
// the marker
var marker = new google.maps.Marker({position: midtown, map: map, draggable: true});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
marker.setPosition(pos);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
// dragged event of the marker
google.maps.event.addListener(marker, 'dragend', function(){
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
var address;
$('#latitude').val(lat);
$('#longitude').val(lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: marker.getPosition()}, function(result,status){
if(status == google.maps.GeocoderStatus.OK){
address = result[0].formatted_address;
// console.log(address);
$('#location_name').val(address);
}
else{
console.log('Geocode was not successful for the following reason: ' + status);
}
});
});
// when the place is changed in the location box the map updates
searchBox = new google.maps.places.SearchBox(document.querySelector( '#location_name' ));
google.maps.event.addListener(searchBox, 'places_changed', function(){
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds();
for(var i = 0; place = places[i]; i++){
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
$('#latitude').val(lat);
$('#longitude').val(lng);
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap"></script>
I updated my first post with the code that is working for me.
I couldn't update the map with the information from the form because I didn't include the places library while loading the Maps JavaScript API.
I couldn't see the updated coordinates after dragging the map marker because I didn't enable the geocoding api and didn't create a billing account with google cloud. I also restricted my API key.
Hope this helps.
Related
I'm fairly new to the Google Maps API and have to use it to locate some addresses. I want to know how the Google Maps marker can be located with the address written in a text field. I've been reading Google's documentation on this, but it hasn't been very helpful.. So far I have managed to make the marker move and update the latitude and longitude values according to the end of the marker movement.
In the html I have this:
<!-- Address input -->
<div class="col-md-3">
<div class="form-group">
<label for="example-text-input" class="form-control-label">Address</label>
<input class="form-control" type="text" name="address" id="address">
</div>
</div>
<!-- shows the current latitude -->
<div class="col-md-3">
<div class="form-group">
<label for="example-text-input" class="form-control-label">Lat</label>
<input class="form-control" type="text" name="latitude" id="lat">
</div>
</div>
<!-- shows the current longitude -->
<div class="col-md-3">
<div class="form-group">
<label for="example-text-input" class="form-control-label">Lng</label>
<input class="form-control" type="text" name="longitude" id="lng">
</div>
</div>
<!-- show the map -->
<div class="row">
<div class="col">
<div class="card border-0">
<div id="map-default" class="map-canvas" style="height: 600px;"></div>
</div>
</div>
</div>
On the js I have this:
var $map = $('#map-default'),
map,
lat,
lng,
color = "#5e72e4";
function initMap() {
map = document.getElementById('map-default');
map = new google.maps.Map(document.getElementById('map-default'), {
zoom: 12,
scrollwheel: true,
center: new google.maps.LatLng(40.71427 , -74.00597),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(4.60971, -74.08175),
map: map,
animation: google.maps.Animation.DROP,
// title: 'Marcador',
draggable: true
});
var infowindow = new google.maps.InfoWindow({
content: String(marker.getPosition())
});
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function(evt){
$("#lat").val(evt.latLng.lat().toFixed(6));
$("#lng").val(evt.latLng.lng().toFixed(6));
map.panTo(evt.latLng);
});
map.setCenter(marker.position);
marker.setMap(map);
}
if($map.length) {
google.maps.event.addDomListener(window, 'load', initMap);
}
To find an address for the marker ( whether that is based upon a click event, drag event or static lat/lng ) you will need to use the Geocoder api - note however that this has a quota limit and contributes to the maps usage statistics! [ see here for details ]
The process is known as reverse geocoding - the geocoder is supplied with a lat/lng value and will return a JSON response with details of the chosen location, from which you can extract the address.
Based upon your original code but without any jQuery
<script>
function initMap(){
const map = new google.maps.Map(document.getElementById('map-default'), {
zoom: 12,
scrollwheel: true,
center: new google.maps.LatLng( 40.71427 , -74.00597 ),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
// initialise the GeoCoder
const geocoder = new google.maps.Geocoder();
const infowindow = new google.maps.InfoWindow();
// utility to populate the input elements with discovered values
const populate=( lat, lng, addr )=>{
document.querySelector('input[name="address"]').value=addr;
document.querySelector('input[name="latitude"]').value=lat.toFixed(6);
document.querySelector('input[name="longitude"]').value=lng.toFixed(6);
};
// function to invoke the geocoder and find the address from given latlng
const findlocation=(e)=>{
geocoder.geocode( { 'location':e.latLng }, ( results, status )=>{
return evtcallback( results, status, e.latLng);
});
};
// respond to clicks on the map
const mapclickhandler=function(e){
findlocation.call( this, e );
};
// respond to clicks on the marker
const markerclickhandler=function(e){
infowindow.open( map, this );
infowindow.setContent( e.latLng.lat()+', '+e.latLng.lng() );
if( this.hasOwnProperty('address') )infowindow.setContent( this.address );
};
// respond to drag events of the marker.
const draghandler=function(e){
findlocation.call( this, e );
map.panTo( e.latLng );
};
// callback function that analyses the Geocoder response
const evtcallback=function( results, status ){
let _address, _location;
if( status == google.maps.GeocoderStatus.OK ){
_address=results[0].formatted_address;
_location=results[0].geometry.location;
// set custom properties for the marker
// which are used to populate infowindow
marker.address=_address;
marker.location=_location;
// populate the HTML form elements
populate( _location.lat(), _location.lng(), _address );
// open and set content for the infowindow
infowindow.open( map, marker );
infowindow.setContent( _address );
latlng=new google.maps.LatLng( _location.lat(), _location.lng() );
marker.setPosition( latlng );
map.setCenter( latlng );
map.setZoom( 15 );
return true;
}
console.warn( status );
};
let marker = new google.maps.Marker({
position: new google.maps.LatLng( 4.60971, -74.08175 ),
map: map,
animation: google.maps.Animation.DROP,
draggable: true
});
google.maps.event.addListener( map,'click', mapclickhandler );
google.maps.event.addListener( marker, 'click', markerclickhandler );
google.maps.event.addListener( marker, 'dragend', draghandler );
map.setCenter( marker.position );
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>
I'm trying to get the Lng and Lat from the marker that I set on the google maps api.
I automatically want the coordinates to take place in my html form.
It looks like I'm not getting the getPosition() right, because every other variable I use (something like var x = 34) does work.
My code:
<form action="send_nieuwcontainer.php" method="post">
Marker_name: <input type="text" name="markername"><br>
Coördinaten: <br>
Lng: <input id="inputlng" type="text" placeholder="<?php $lng; ?>" readonly="readonly">
Lat: <input id="inputlat" type="text" placeholder="<?php $lat; ?>" readonly="readonly"><br>
</form>
</div>
<script>
function initMap() {
var groningen = {lat: 53.218883, lng: 6.566298};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: groningen
});
map.addListener('click', function(e) {
clearMarkers();
addMarker(e.latLng, map);
});
}
var markers = [];
var lng = marker.getPosition().lng();
var lat = marker.getPosition().lat();
document.getElementById('inputlng').value = lng;
document.getElementById('inputlat').value = lat;
// Adds a marker to the map.
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
markers.push(marker);
if (marker = true) {
document.getElementById('replaceMe').style.display = 'none';
document.getElementById('replacement').style.visibility = 'visible';
} else {
alert ("Does not work");
}
}
Does someone see what I'm doing wrong or maybe something I'm forgetting?
Note: I've already tried looking on stackoverflow and googlemaps api guide. They keep telling me to use getPosition()
As #Turnip said, the marker var is declared with var inside addMarker, so it's only accessible inside addMarker.
Try declaring marker outside the function like var marker; and then, inside the function, instead of using var marker = ..., use marker = ....
I am trying to display a map, zoom into a zipcode, and then place Congressional District overlay onto map. The overlay is here: https://www.google.com/fusiontables/DataSource?snapid=S506424n-DY
I downloaded the KML link file, and saved it onto my local IIS server. However, the overlay never is drawn.
I also added the following mime types to my IIS Server:
.kml application/vnd.google-earth.kml+xml
.kmz application/vnd.google-earth.kmz
The kml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<NetworkLink>
<name><![CDATA[2012 US Congressional Districts]]></name>
<Link>
<href>
https://www.google.com/fusiontables/exporttable?query=select+col5+from+1QlQxBF17RR-89NCYeBmw4kFzOT3mLENp60xXAJM&o=kmllink&g=col5</href>
</Link>
My HTML/javascript looks like:
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script language="javascript">
var map;
var marker;
function showAddress() {
$("#divGoogleMap").css('display', '');
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("divGoogleMap"), mapProp);
myListener = google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'drag', function (event) {
placeMarker(event.latLng);
});
var zipCode = $("#txtZip").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Got result, center the map and put it out there
var pos = results[0].geometry.location;
saveLocation(pos);
map.setCenter(pos);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: pos
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var kmlUrl = '/DesktopModules/HelloWorld/2012_US_Congressional_Districts.kml';
var kmlOptions = {
suppressInfoWindows: true,
preserveViewport: false,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
saveLocation(location);
}
function saveLocation(pos) {
$("#hfLatitude").val(pos.lat());
$("#hfLogitude").val(pos.lng());
}
</script>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<td>
<asp:TextBox ID="txtZip" ClientIDMode="Static" runat="server"></asp:TextBox>
</td>
<td>
<input type="button" id="btnSearch" value="Search" onclick="showAddress()" />
</td>
</tr>
</table>
<div id="divGoogleMap" style="width: 800px;height: 600px;display: none;"></div>
<asp:HiddenField ID="hfLatitude" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="hfLongitude" ClientIDMode="Static" runat="server" />
What am I doing wrong here?
For use in google maps th kml must be located in an accessible server e not in local.
This is form google doc.
Overview
The Google Maps API supports the KML and GeoRSS data formats for
displaying geographic information. These data formats are displayed on
a map using a KmlLayer object, whose constructor takes the URL of a
publicly accessible KML or GeoRSS file.
the constructor take the URL of a publicly accessible KML.
Then for yoour need you must place your kml in a publicly accessible server
I had forgotten that i had already had a similar experience some years ago and the solution was precisely to place the files kml on a server accessible from the Internet.
I am in a situation where I need to draw Google map using api v3 with multiple locations. These location can be static address string like "New Delhi, India" or 110005, but they will be several in numbers - can be comma separated or an array - i dont know exactly how they need to be put in the code. But simply i want to draw gmap with multiple locations, so a given map will have 9 or 10 location at once. How to do that? Can you please give me any working code on jsfiddle. For now my code to draw a gmap with only a single location (address only and not zip code) is given below -
JavaScript -
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize()
{
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress()
{
//var address = "Talwara Township, Punjab";
var address = document.getElementById("txtaddress").value;
geocoder.geocode({'address': address}, function(results, status){
if(status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: "New Delhi, India"
});
infowindow.open(map, marker);
// Click the marker to Zoom to 9
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
});
}
</script>
HTML -
<body onLoad="initialize();codeAddress();">
<form method="get" action="">
<input type="text" id="txtaddress" name="txtaddress" size="30" value="New Delhi, India" />
<input type="submit" name="btnsubmit" value="Generate Map" />
</form>
<br /><br />
<div id="map_canvas" style="width:500px; height:380px; border:1px solid #AFAFAF;"></div>
</body>
What you are asking is Batch GeoCoding. The process of changing multiple addresses into a Geographical location is referred to as Batch GeoCoding.
Google Maps API is not directly supporting BatchGeocoding.
By using Google Maps API , We do geocode a single address at a time.
To acheive BatchGeoCoding, We need to iterate a list of Address.(Not too difficult I think)
For best Practice : GeoCode Example
BatchGeocode Reference :
The following are online batch Geocoding sites. Have it for reference.
Ref 1 , Ref 2
Working Demo
The Working demo is just a Proof of the Concept. It has to be refined in many ways. Please have a look at the reference to produce a better code.
This question already has answers here:
How to find the lat lng from a geocoded address?
(2 answers)
Closed 8 years ago.
so I'm looking for a way to pass the latitude and longitude from google maps api to a php textfield.
So far I have the following code but I'm stuck, any help would be much appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script>
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(51.8978719,-8.471087399999988),
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
citMarker=new google.maps.Marker({
position:new google.maps.LatLng(51.885403000000000000,-8.534554100000037000),
animation:google.maps.Animation.BOUNCE
});
var infowindow = new google.maps.InfoWindow({
content:'<b>Cork IT</b>'
});
infowindow.open(map,citMarker);
citMarker.setMap(map);
google.maps.event.addListener(citMarker, 'click', function() {
map.setZoom(15);
map.setCenter(citMarker.getPosition());
infowindow.open(map,citMarker);
});
google.maps.event.addListener(map, 'rightclick', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var lat = location.lat();
var long = location.lng();
window.location.href = "testmap.php?dlat=" + lat + "&dlong=" + long;
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<?php
function getLatLong() {
// Check if we have parameters dlat and dlong being passed to the script through the URL
if (isset($_GET["dlat"]) && isset($_GET["dlong"])) {
// Put the two words together with a space in the middle to form "hello world"
$lat = $_GET["dlat"];
$long = $_GET["dlong"];
// Print out some JavaScript with $hello stuck in there which will put "hello world" into the javascript.
echo $hello;
echo $lat;
echo $long;
}
}
?>
getLatLong();
Lat 1:<input type="text" size="20" maxlength="50" name="displayLat" value="<?php echo $lat; ?>"><br />
Long 1:<input type="text" size="20" maxlength="50" name="displayLong"><br />
</body>
</html>
So far it is displaying a google map, when you right click on the map an infowindow pops up giving the coordinates for the space, and 2 textfields are displayed below the map, what I am looking to do is to display the latitude and longitude in the form when you right click the map.
You can put the latitude and longitude of the right click event in the HTML form like this:
google.maps.event.addListener(map, 'rightclick', function(event) {
document.getElementById('displayLat').value = event.latLng.lat();
document.getElementById('displayLong').value = event.latLng.lng();
placeMarker(event.latLng);
});
If you give your <input> tags ids:
Lat 1:<input type="text" size="20" maxlength="50" name="displayLat" id="displayLat" value=""><br />
Long 1:<input type="text" size="20" maxlength="50" name="displayLong" id="displayLong"><br />