Google Maps Api - javascript

i'm having a problem with Google Maps api integration for form autocomplete.
I have implemented it and works properly until i try to restrict by country.
<script>
function initialize() {
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(40.802089, -124.163751)
);
var origin_input = document.getElementById('location');
//var isocode = document.getElementById('ISOcountry').val()
var options = {
bounds: defaultBounds,
types: ['(cities)'],
language: '<?php echo $lang['dataLanguage']?>',
//componentRestrictions: {country: isocode }
};
var autocomplete_origin = new google.maps.places.Autocomplete(origin_input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
if i uncomment the 2 lines for componetRestrictions it doesn't work and i don't understand why.
var isocode = document.getElementById('ISOcountry').val()
get the ISO country value from here:
Do you guys have any idea?
Also i would like to optimize the script getting the ISO code directly from another script attached here:
$.post('libs/jsonISOcountry.php', { country : val }, populateISOcountry, 'html');
function populateISOcountry(data) {
$('#ISOcountry').html(data);
}
Content of the page jsonISOcountry.php
//....DB connection.....
if (!empty($_POST['country'])) {
foreach ($conn->query("SELECT * FROM regions WHERE countryID=".$_POST['country']) as $row3) {
$html = $row3['isocountry'] ;
}
die($html);
Thanks in advance for you help

Found out the issue!
var isocode = document.getElementById('ISOcountry').val()
wasn't working on hidden field of the form!
changed with this one and working properly!
var isocode = document.getElementById('ISOcountry').value;

Related

How to build Leaflet control located with marker draggable(update lat/long when drag) & auto update value in lat/long form

I had the existing code which already built with located control and auto update lat/long in value web form(see attached)
Now I want to add a draggable maker when my location is detected and auto update the lat/long when maker pin point changed focus on located control function. My search control function work as expected, it was using markerz as maker.
Here was my existing code:
<script type="text/javascript">
var mymap = L.map(\'dvMap\').setView(['. $pin_lat . ', ' . $pin_long . '],13);
L.tileLayer(\'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}{r}.png\',{maxZoom: 18,attribution: \'\'}).addTo(mymap);
var markerz = L.marker([' . $pin_lat . ', ' . $pin_long . '],{draggable:
true}).addTo(mymap);
var searchControl = new L.Control.Search({url:
\'//nominatim.openstreetmap.org/search?format=json&q={s}\',jsonpParam:
\'json_callback\',
propertyName: \'display_name\',propertyLoc:
[\'lat\',\'lon\'],marker: markerz,autoCollapse: true,autoType:
true,minLength: 2,});
searchControl.on(\'search:locationfound\', function(obj) {
var lt = obj.latlng + \'\';
var res = lt.split("LatLng(" );
res = res[1].split( ")" );
res = res[0].split( ","
);
document.getElementById(\'map_lat\').value = res[0];
document.getElementById(\'map_long\').value = res[1];
});
mymap.addControl( searchControl );
markerz.on(\'dragend\', function (e) {
document.getElementById(\'map_lat\').value =
markerz.getLatLng().lat;
document.getElementById(\'map_long\').value =
markerz.getLatLng().lng;
});
L.control.locate({
strings: {
title: "Show me where I am!"
}
}).addTo(map);map.on(\'locationfound\',(e)=>{
console.log(e);
document.getElementById(\'map_lat\').value = e.latlng.lat;
document.getElementById(\'map_long\').value = e.latlng.lng;
});
</script>
You need to call setLatLng() on the marker:
map.on(\'locationfound\',(e)=>{
console.log(e);
markerz.setLatLng(e.latlng);
document.getElementById(\'map_lat\').value = e.latlng.lat;
document.getElementById(\'map_long\').value = e.latlng.lng;
});

Getting intermittent 'google not defined' and other errors using maps api v3

My application makes api calls to the census and uses that data in combination with Google Maps API v3. It works as expected much of the time, but I’m getting an intermittent error of ‘Initmap is not defined’, or ‘google is not defined’, or ‘TypeError: map.data.getFeatureById(...) is undefined’ without any discernible reason.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=KEY1234&callback=initMap" async defer
></script>
<script src="js/mapfunc.js"></script>
</head>
<body>
<div id="map"></div>
<script>var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 35, lng: -106}
});
}</script>
</body>
</html>
JS:
function loadMapShapes() {
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName: 'STATE' });
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
loadCensusData(variable);
}
function loadCensusData(variable) {
// load the requested variable from the census API
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.census.gov/data/2014/acs5/?get=' +
variable + '&for=state:*&key=KEY123');
xhr.onload = function() {
var censusData = JSON.parse(xhr.responseText);
censusData.shift(); // the first row contains column names
censusData.forEach(function(row) {
censusMin = 0;
censusMax = 36000000;
var censusVariable = parseFloat(row[0]);
var stateName = row[1];
var stateId = row[2];
// keep track of min and max values
if (censusVariable < censusMin) {
censusMin = censusVariable;
}
if (censusVariable > censusMax) {
censusMax = censusVariable;
}
// update the existing row with the new data
coolid = map.data.getFeatureById(stateId);// <-- Here's where
//I get the error most often: "TypeError: map.data.getFeatureById(...) is undefined"
if (coolid !== undefined) {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
map.data
.getFeatureById(stateId)
.setProperty('census_variable1', stateName);
}
coolstate = map.data.getFeatureById(stateName);
});
Again - this code works maybe 40% of the time, and throws one of the above-described errors the rest of the time. I may notice an increase in errors during the day but can't be sure.
Thanks a lot for any thoughts, here's a link to a live version of this code with census and google maps API calls:
http://dukecitydigital.com/c1/
loadGeoJson runs asynchronously, use the callback of loadGeoJson to execute further functions which depend on the result of loadGeoJson:
function loadMapShapes() {
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName:'STATE'}, function(){
loadCensusData(variable);
});
}
Here is the code I am using to avoid 'undefined' error:
// update the existing row with the new data
if (typeof(map.data.getFeatureById(stateId)) != "undefined") {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
}

Uncaught TypeError: Cannot call method 'getElementsByTagName' of null

I have spent so much time trying to fix this bug. I really don't know what the issue is.
http://pastebin.com/wXEHsqeY is where the code is. The error points to leaflet library kml.js but I have not touched this file. The error seems to be coming from lines 366-390 as when I remove them there is no error.
I would really appreciate any help anyone can offer.
Thanks
Update: apologies for using the wrong format, please see a more basic example of what Im stuck on.
<body>
<div style="width:100%; height:100%" id="map"></div>
<?php
function getKmlFiles() {
$folder = 'kml/';
$filetype = '*.*';
$files = glob($folder.$filetype);
for ($i=0; $i<count($files); $i++) {
echo '"' . $files[$i].'",';
}
}
?>
<script>
var kmlArray = [<?php getKmlFiles(); ?>];
console.log(kmlArray);
var map = new L.Map('map', {center: new L.LatLng(58.4, 43.0), zoom: 11});
var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var track = new L.KML("http://localhost/kmllayer/kml.kml", {async: true});
track.on("loaded", function(e) { map.fitBounds(e.target.getBounds()); });
map.addLayer(track);
map.addLayer(osm);
var object ={'THW-UK2 (R)':track};
for (var i=0; i<kmlArray.length; i++) {
var kmlLayer = new L.KML("http://localhost/kmllayer/" + kmlArray[i] , {async: true});
object[kmlArray[i]] = kmlLayer;
map.addLayer(kmlLayer);
kmlLayer.on("loaded", function(e) {
map.fitBounds(e.target.getBounds());
});
map.addLayer(kmlLayer);
}
console.log(object);
map.addControl(new L.Control.Layers({}, object, {}));
</script>
<script type='text/javascript'>
map.on( "zoomend", function( e ) {
console.log( "zoom level is " + map.getZoom() )
});
map.on( "zoomend", function( e ) {
zoom = map.getZoom( );
if ( zoom <= 3 ) {
alert('zoomed out');
}
});
</script>
you are opening php in your js file at line 366
var kmlArray = [<?php getKmlFiles(); ?>];
if you want to use the values of php in js file make a variable global and call it in your js file.
<script>
abc = "<?php getKmlFiles(); ?>";
</script>
in your js files
var kmlArray = abc;
For anyone who encountered a similar problem, the cause was the kml files were saved as .kmz files but weren't actually zipped. Issue solved now.

Google Map javascript MarkerManager markers not showing

I have a map that reads an XML file; it's all very simple and copied from here:
http://geochalkboard.wordpress.com/2009/03/30/reading-xml-files-with-the-google-maps-api/
My version is here:
http://www.cloudfund.me/maps/mashup.html and the data file it's reading is here:
converted.xml in the same directory.
I don't get any points at all, when I run it. I put some console logging in to see if I could see anything, but as far as that's concerned, it just runs through without a hitch. The file loads ok, and I can watch the code loop through all the rows (208 in this example) without any problems.
The only warning I'm getting is the 'Resource interpreted as other passed as undefined' one; having had a look at some of the other threads, I can't see anything that helps - no empty src links, etc. As far as I can tell, this shouldn't stop it marking the points, either.
Here's the real kicker - in trying to trace this error, I set up an exact replica of the original code on my own server, and got an error about null fields, which I added some conditional code to to sort; this version works on my server. This is austin.html in the same directory (sorry, can't do more than two links in my first posts!)
So - my code is this:
<title>Test </title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
type="text/javascript">console.log("Loaded Maps API");</script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js">console.log("MarkerManager");</script>
<script type="text/javascript">
console.log("Into Main Script");
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(51.39906378, -2.449545605), 13);
map.setUIToDefault();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_PHYSICAL_MAP);
console.log("Reached end of map initialising");
addMarkersFromXML();
console.log("MarkersfromXML")
}
}
function addMarkersFromXML(){
var batch = [];
mgr = new MarkerManager(map);
var request = GXmlHttp.create();
console.log("About to open converted.xml")
request.open('GET', 'converted.xml', true);
console.log("Opened Converted.xml")
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
{
var xmlDoc = request.responseXML;
var xmlrows = xmlDoc.documentElement.getElementsByTagName("row");
for (var i = 0; i < xmlrows.length; i++) {
var xmlrow = xmlrows[i];
console.log("Running through row number",i)
var xmlcellLongitude = xmlrow.getElementsByTagName("longitude")[0];
console.log(xmlcellLongitude);
var xmlcellLatitude = xmlrow.getElementsByTagName("latitude")[0];
var point = new GLatLng(parseFloat(xmlcellLatitude.firstChild.data),parseFloat(xmlcellLongitude.firstChild.data));
//get the PAO
var xmlcellAssetName = xmlrow.getElementsByTagName("pao")[0];
console.log(xmlcellAssetName);
var celltextAssetName = xmlcellAssetName.firstChild.data;
//get the area
var xmlcellArea = xmlrow.getElementsByTagName("area")[0];
console.log(xmlcellArea);
var celltextArea = xmlcellArea.firstChild.data;
//get the land type
var xmlcellLandType = xmlrow.getElementsByTagName("landtype")[0];
console.log(xmlcellLandType);
var celltextLandType = xmlcellLandType.firstChild.data;
//get the Planning Permissions
var xmlcellPlanning = xmlrow.getElementsByTagName("planning")[0];
console.log(xmlcellPlanning);
var celltextPlanning = xmlcellPlanning.firstChild.data;
var htmlString = "Asset Name: " + celltextAssetName + "<br>" + "Size: " + celltextArea + "<br>" + "Land Type: " + celltextLandType + "<br>" + "Planning Permissions: " + celltextPlanning;
//var htmlString = 'yes'
var marker = createMarker(point,htmlString);
batch.push(marker);
}
mgr.addMarkers(batch,50);
mgr.refresh();
}
}
request.send(null);
}
function createMarker(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1100px; height: 700px"></div>
</body>
</html>
Think you have a typo. In your code, you're pulling an incomplete URL for the API:
<script src="//maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
That errant // seems to be throwing the code off.
Though, to be perfectly honest, the originating example (and austin.html) doesn't exactly work as one would imagine it should. The points do get rendered, but no effective clustering takes place when you zoom out. Suspect that the 2.0 branch of the API got moved to a newer version and created a bit of an incompatibility.
Recommend that you rewrite this in API version 3. There is a cluster manager that works for it quite well.
See http://tools.voanews2.com/nuclear_reactors/

How can I fix this JavaScript syntax error?

This is puzzling me. I'm using Google Map's Geocoding to find locations. I am attempting to use the example here, which is from Google, and it is just not working for me.
Error:
http://maps.gstatic.com/intl/en_us/mapfiles/159e/maps2.api/main.js
Line 174
var point = new GLatLng(,);
Code:
<script src="http://maps.google.com/maps?file=api&v=2&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>
<style type="text/css">
#import url("http://www.google.com/uds/css/gsearch.css");
#import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
<script type="text/javascript">
function addListener(element, baseName, handler) {
if (element.addEventListener)
element.addEventListener(baseName, handler, false);
else if (element.attachEvent)
element.attachEvent("on"+baseName,handler);
}
var map'.$num.';
function initialize'.$num.'()
{
if (GBrowserIsCompatible())
{
map'.$num.' = new GMap2(document.getElementById("google_map'.$num.'"),{mapTypes:[G_HYBRID_MAP]});
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
map'.$num.'.setCenter(new GLatLng('.$row->LocationLat.','.$row->LocationLon.'),4);
var mapControl = new GMapTypeControl();
map'.$num.'.addControl(mapControl);
map'.$num.'.addControl(new GLargeMapControl());
map'.$num.'.addControl(new GOverviewMapControl());
map'.$num.'.enableDoubleClickZoom();
map'.$num.'.enableScrollWheelZoom();
var bounds = new GLatLngBounds;
var myIcon = new GIcon();
myIcon.image = "http://www.google.com/mapfiles/marker.png";
myIcon.iconAnchor = new GPoint((markerImage1.width/2),markerImage1.height);
bounds.extend(point);
setBounds(map'.$num.',bounds);
var address = "' . $address . '";
var geocoder = new GClientGeocoder();
showAddress(address, geocoder);
}
}
function showAddress(address, geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map'.$num.'.setCenter(point, 13);
var marker = new GMarker(point);
map'.$num.'.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
function setBounds(map'.$num.',bounds)
{
map'.$num.'.setZoom(15);
map'.$num.'.setCenter(bounds.getCenter());
}
function chargement()
{
markerImage1 = new Image();
markerImage1.src = "http://www.google.com/mapfiles/marker.png";
setTimeout("initialize'.$num.'()", 500);
}
addListener(window, "load", chargement);
</script>
My code is generated by PHP, so when there is an ' that means I'm opening or closing the string that is holding the JavaScript.
Maybe I didn't get it, but
var point = new GLatLng(,);
is not valid javascript
It should be either
var point = new GLatLng(param1, param2);
or
var point = new GLatLng();
or
var point = new GLatLng(null,null);
... depending on what the GLatLng constructor is
This statement:
var point = new GLatLng(,);
Is not correct because there isn't a lat or lng number specified. This is because this statement:
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
Is incorrect. I'd try something like:
var point = new GLatLng(<?php echo $row->LocationLat . ',' . $row->LocationLon; ?>);
If that doesn't work, then $row->LocationLat or $row->LocationLon are possibly empty.
Problem 1- The function showAddress() is not closed.
Problem 2 - your map object needs to be defined outside of the functions so that showAddress() can access it.
Problem 3 - The references to the map object inside of showAddress() are incorrect
check if the php string you are printing into the html+js exists in the first place. php generates the htm and sends it to the user, for now on it's htm+javascript problem.
it looks like a javascript problem, but you really generated a wrong syntax with php to begin with, because you tried to print something problematic and it printed an empty space.
always be careful of that, be sure of what you print.

Categories

Resources