Multiple maps not working for Google maps - javascript

I have some jquery (below) with creates multiple maps on window load. However there is some strange behaviour with the maps, but no errors.
The problem is when the maps load they all have the same location on the map, even when multiple different lng and lats are set.
Below is the the code that create the map and some sample html of one of the maps's boxes.
The strange thing is that the maps have the same locations but there are not errors. Has anyone experienced this before or know why it's happening.
Cheers.
Js: (assume this is called onloand and some blank global arrays are set.)
var maps_boxes = {
initialise: function() {
$('.a_map').each(function(index) {
var map_box = $(this);
var map_id = map_box.find('.the_map').attr('id');
var lat = map_box.find('.lat').val();
var lng = map_box.find('.lat').val();
lat_lngs[index] = new google.maps.LatLng(lat,lng);
options[index] = {
zoom: 4,
center: lat_lngs[index],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
maps[index] = new google.maps.Map(document.getElementById(map_id), options[index]);
});
}
};
Sample html of one map:
<div class="a_map">
<form class="map_data" >
lng:<input class="lng" type="text" value="0" /><br />
lat:<input class="lat" type="text" value="10" />
</form>
<div id="map_xxxxx" class="the_map" ></div>
</div>

If you are using the same code you posted, you are getting same value for both the latitude and longitude:
var lat = map_box.find('.lat').val();
var lng = map_box.find('.lat').val();
I tried initializing 2 different maps on same page it is working fine.

Related

setting marker coordinates as variable

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 = ....

Linking Google Script Variable to the Javascript in HTML

So I feel I'm almost there to the solution but I'm really in need of help here. What I'm trying to do is to create an array using .getValues() to get a range that contains four columns (Name, Address, Latitude, and Longitude). After that I want to return the variable back into a global variable and then call that variable from the HTML side. I tried linking the google script with the HTML and then calling the variable there but having quite a bit of trouble with that. Thank you guys for all of your help!
Below is the google script:
var id = 'Spreadsheet Key';
function doGet(e) {
var html = HtmlService.createTemplateFromFile('Sample');
return html.evaluate().setTitle('Directory Map');
}
function entries() {
var blop =
SpreadsheetApp.openById(id).getSheetByName('Sheet1').getRange('A1:D').getValues();
return blop;
}
This is the HTML in Google Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.8283, lng: -98.5795},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'greedy'
});
var locations = [blop];
for (var i = 0; i < locations.length; i++) {
var sites = locations[i];
var myLatLng = new google.maps.LatLng(sites[2],sites[3]);
var sites = new google.maps.Marker({
position: myLatLng,
map: map,
title: sites[0],
});
};
}
</script>
<script> google.script.run.entries(); </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&libraries=places&callback=initAutocomplete"async defer></script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="SampleCode.gs"></script>
</body>
</html>
The starting point is:
<script> google.script.run.entries(); </script>
The above code runs when the page is loaded in the browser. You need a "success handler", and then the success handler can store the data somewhere. You could put the data into a window variable, or local browser storage.
<script>
window.storeSheetValues = function(theReturnedData) {
console.log('theReturnedData: ' + theReturnedData)
console.log('typeof theReturnedData: ' + typeof theReturnedData)
window.mySheetData = theReturnedData;//Put the data into a window variable
}
google.script.run
.withSuccessHandler(storeSheetValues)
.entries();
</script>
Check the data type of the return value coming back from the server. If it's a string, you may want to turn it back into an array.

How to refer to a function in HTML?

I am making an html file that basically prints out the coordinates given by the user in a map. Whenever I click the submit button, it returns me an error of "UncaughtReferenceError: NewMap is not defined" i tried using an external javascript and inline javascript but it does not seem to solve the problem. Can you tell me what is wrong with the code?
<!DOCTYPE html>
<html>
<head>
<title>Find My Phone</title>
</head>
<body bgcolor="#2196F3">
<p style="font-size:150%; text-align:center">This is the extension for the app FindMyPhone. In this site, you can view the coordinates where your phone was traced on a map</p>
Latitude:
<input type="number" step="any" id="Lat"/> <br>
Longitude:
<input type="number" step="any" id="Lng"/> <br>
<button onclick="NewMap()">Submit</button>
<div id="map" style="height:500px;width:500px; color:#9E9E9E">
</div>
<script>
function NewMap() {
var mapCanvas = document.getElementById("map").value;
var Latitude = document.getElementById("Lat").value;
var Longitude = document.getElementById("Lng").value;
var mapOptions = {
center: document.getElementById("Lat, Lng")
zoom:15
}
var map = new.google.maps.Map (mapCanvas, mapOptions)
}
</script>
</body>
</html>
P.S: Supposing this code works, will it output the map correctly? Please also show me if it is right or wrong.
Include Google Map Library
You have missed out a comma after center property.
var mapOptions = {
center: document.getElementById("Lat, Lng"),
zoom:15
}

Set and drag a Marker on Leaflet-map updates form input-field without sending

including leaflet and jQuery in the head, I have this code:
<form name="formone"> ...
<div id="clickmap">
<div id="map"></div>
<script type="text/javascript">
var map = L.map('map').setView([34.00, 8.00, 6);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map);
function onMapClick(e) {
var lat = (e.latlng.lat);
var lng = (e.latlng.lng);
var marker = L.marker([lat, lng], {draggable:true}).addTo(map).bindPopup($('Remove ME').click(function() { map.removeLayer(marker); })[0]);
// latnew = marker._latlng.lat; // test
// latold = document.formone.GPSLatitude.value; // test
}
map.on('click', onMapClick);
// function simply() {} // test
</script>
</div><!-- end clickmap -->
...
<input type="text" name="GPSLatitude" onclick="javascript:simply();" value="<?php echo $GPSLatitudeDec; ?>" size="25" maxlength="20" />
...
... </form>
With a click, I set a marker on the map.
In this procedure I would like to update the input-field,
before submitting. Also, if I drag the marker on the map,
the input-field should become updated.
And the last marker can become deleted too,
so that I've to deal only with one marker.
Can someone give me an overview, how to do that?
I'm not to exercised in the jQuery- or Leaflet-libaries.
Are there any functions workarounds prepared?
Thank you,
Rob
If you have two textboxes on your page, how about updating their values from inside the onMapClick(e) function?
...
<p>Latitude: <input id="latInput"> :: Longitude: <input id="lngInput"></p>
<script>
...
function onMapClick(e) {
... //whatever code you've already put
document.getElementById('latInput').value = lat;
document.getElementById('lngInput').value = lng;
}
...
</script>
Edit: Similar answer shared here as well: https://stackoverflow.com/a/27272673/4355695, with working example : http://plnkr.co/edit/iyMhaoAyllr2uNSOHhS9?p=preview
Edit: worked out a full solution with both drag and click, and having reverse functionality too (user-entered values in form fields can move the marker). It also remembers the previous location marked by the user. See
working example: http://plnkr.co/edit/PTFlun?p=preview

How can I draw google map using api v3 with multiple locations (address as well as zip codes)?

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.

Categories