Multiple Google Maps icons? - javascript

I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.

It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.

The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.

Related

Google maps API - add marker by address javascript

I have database of places with addresses and I want to add markers on google maps.
It shows only the default marker, seems like the geocoder.geocode() does nothing. For an example I'm trying to add a marker on " New York City", with no success.
<script>
var geocoder;
var map;
var address = "new york city";
geocoder = new google.maps.Geocoder();
function initMap() {
var uluru = { lat: -25.363, lng: 131.044 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
var marker = new google.maps.Marker({
position: address,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
async defer></script>
The reason why you are not getting the expected result is because there is incorrect codes placement in the example you provided. You are trying to get a new instance of Google Maps API Geocoder before Google Maps is fully loaded. Hence, Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined. You should get a new instance of Google Maps API Geocoder inside the initMap() function.
You can check Maps JavaScript API Geocoding
to learn more.
You can also check Best Practices When Geocoding Addresses.
Please also note that you should not include your API_KEY when posting Google Maps APi related questions.
Here's the whole code:
<!DOCTYPE html>
<html>
<head>
<title>Geocoding service</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var geocoder;
var map;
var address = "new york city";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
geocoder = new google.maps.Geocoder();
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Live demo here.
Hope it helps!
There were several errors in your code. Normally, it should looks OK now:
var geocoder;
var map;
var address = "new york city";
function initMap() {
geocoder = new google.maps.Geocoder();
var uluru = { lat: -25.363, lng: 131.044 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
console.log(results);
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
console.log (latLng);
if (status == 'OK') {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
console.log (map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
This is a list of your errors:
You have to initialize your geocode when the google maps api is fully loaded. It means that you have to put this line of code:geocoder = new google.maps.Geocoder(); in the initMap ().
When you initialize the map you have to refer to a global variable. In your code, you create a new variable map in your function. But, you have to pass by the global's variable map.
When, you want to get the position of the geocoder's result, you have to pass by this line of code:results[0].geometry.location.lat ().
You may refer to the documentation.
Tell me if you have some questions.

Uncaught error: google is not defined for Google Map API geocoder

Hey Im currently using the Google API to render a map onto my application; however, I am running into a problem where Im using the Google's Geocoding library but it is running into an uncaught error: google is not defined.
I dont understand this error, because I use it to render the map itself, and the google object is being read and rendering the map fine.
Here is my html scripts:
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="js/scripts.js" async></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap" async defer>
</script>
And here is my javascript file:
function initMap() {
var geocoder = new google.maps.Geocoder(),
fromLatLng = getLatLng(geocoder, "Pasadena, California"),
startLatLng = getLatLng(geocoder,"Los Angeles, California"),
fromLocation = new google.maps.LatLng(fromLatLng),
destLocation = new google.maps.LatLng(startLatLng),
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
console.log(fromLocation)
renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
return results[0].geometry.location;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
I've tried changing around the scripts and a lot of other stackoverflow posts but havent found any luck.
Your geocode use wasn't right.
I have to admit that it was a tricky one!
I never used that service before... I even had to enable it!!
What I found out is that it has a delay to retreive the info.
Yeah... It's a get request after all...
And you do it twice.
So what I did is to set an interval to check if both 2 Geocode resquests callback had executed before setting the map, since needed to set the markers.
I implemented it in a new function which I called doGeocode().
This is also your map API callback in the script call, instead of initMap.
This function, after getting the 2 geocodes latitude/longitude, finally calls the initMap() to render your desired result.
The only thing I couldn't find out is your renderRoute function... Since not provided in your question. But I think you will be able to handle it.
So... Have a look at the result on my server here.
The full code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>SO # 39909383</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Google Maps CSS-->
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:300">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
cursor: pointer !important;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var fromLocation;
var destLocation;
var callbackCounter=0;
function initMap() {
console.log("Map initialisation");
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7, // continent level
mapTypeId: google.maps.MapTypeId.SATELLITE // TERRAIN, HYBRYD, ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionRender = new google.maps.DirectionsRenderer({
map: map
});
var markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
});
var markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
// renderRoute == not a function!!
// Missing in the question...
// Temporarly commented out.
//
//renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
console.log("callbackCounter: "+callbackCounter);
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
// Only to see clearly in console.log()
var latlong = JSON.stringify(results[0].geometry.location);
console.log( latlong );
latlong = JSON.parse(latlong);
callbackCounter++;
// Set from
if(callbackCounter==1){
fromLocation = latlong;
}
// Set dest
if(callbackCounter==2){
destLocation = latlong;
}
// Function end.
return;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
function doGeocode(){
var geocoder = new google.maps.Geocoder();
getLatLng(geocoder, "Pasadena, California");
getLatLng(geocoder,"Los Angeles, California");
// Wait for from and dest locations found ( Geocoder get delay )
var waitForCoords = setInterval(function(){
console.log("--- Interval");
if(callbackCounter==2){
clearInterval(waitForCoords);
console.log("--- Interval cleared");
// Ready to initialise the map!
initMap();
}
},50);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=doGeocode"></script>
</body>
</html>

Google Map API marker update from JS

I would like to ask you a solution for this problem.
I have a JS with a variable inside that is updated overtime by a JAVA application (i.e. JAVA writer into a thread), after that I take the coordinates from that variable and I create a new object Marker for my google maps. The problem is that the marker does not changes position, it changes only if I refresh the whole page (I dont want to do this).
Here's the code to be more clear.
The inputData.js where the variable is written by the java application
var newMarker = {'latitude':38.25705300000004,'longitude': 140.83760400000006};
my html page used to display the map
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY">
</script>
<script type="text/javascript" src="inputData.js"></script>
<script>
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
setInterval(refreshData, 2000);
function refreshData() {
var marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I open my page like this everything work but when I change the script "inputData.js" the marker does not changes position.
The method setCenter on the other hand seems to work properly.
Help me please!
You'll need to reload the updated script to get the updated position:
function initialize() {
var mapOptions = {
zoom: 18,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP},
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//we will store the LatLng here
pos = new google.maps.MVCObject(),
//use a single marker with updated position
marker = new google.maps.Marker();
//set the latLng of the MVCObject
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
//bind the markers position to the latLng of the MVCObject
marker.bindTo('position',pos,'latLng');
marker.setMap(map);
setInterval(function(){
//the currently loaded script
var script=document.querySelector('script[src^="inputData.js"]'),
//the updated script
update=document.createElement('script');
//load-handler for the updated script
google.maps.event.addDomListenerOnce(update,'load',function(){
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
map.setCenter(pos.get('latLng'));
map.setZoom(18);
});
//replace current script with updated script
script.parentNode.replaceChild(update,script);
//load update
update.src='inputData.js?'+new Date().getTime();
},2000);
}
You don't need to create new instance of marker every time. Update your code with this and try:
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
var marker;
marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
setInterval(refreshData, 2000);
function refreshData() {
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);

Uncaught Reference Error: None is not defined

New to javascript. Trying to add a list of markers (from python) to a google map.
My raw Jinja2 template:
<head>
<title>Google Map Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
#map-canvas { height: 700px; width: 400px; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=false">
</script>
<script type="text/javascript">
var locations = {{ locations|safe }};
/*
locations|safe results in the following line in my rendered template:
var locations = [['A.W. Hastings / Windows & Doors by Brownell', '44.4456', '-73.1276'], ['AARP', '44.4757', '-73.2113'], ['Adirondack Audiology', '44.4792', '-73.22'], ['Alchemy Jewelry Arts #1A', '44.4672', '-73.2147'], ['All Smiles Dental', '44.2334', '-72.5539']];
*/
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.953, -72.593),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (var i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
I send the list "locations" from my view because the list changes regularly.
I am receiving the Uncaught Reference Error for the line where I define the locations variable. The full output is:
Uncaught ReferenceError: None is not defined 127.0.0.1:14
(anonymous function)
Move the code that follows the function initialize() inside the function, otherwise the variable map is not available when and where you access it.

Fetching nearby locations from google places and adding markers on google map from results

EDIT: SOLVED. Correct code below the problem code.
I'm having trouble getting my code to work. What I want to do is to use geolocation to determine the users location. I then want to do a search to locate something from a string (in this case, "Systembolaget", in a radius of 2000, and show the results on a google map. I get my own location on the map, but i'm having big trouble getting the places results.
What am I doing wrong? I don't have that much experience from javascript, so all help is good help.
If you're wondering about the cordova script, it's necessary since I'm doing a phonegap application.
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="cordova-1.6.0.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYAPIKEY&sensor=true"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '2000',
name: ['Systembolaget']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for ( var i = 0; i < results.length; i++ )
{
var place = results[i];
var loc = place.geometry.location;
var marker = new google.maps.Marker
({
position: new google.maps.LatLng(loc.Pa,loc.Qa)
});
marker.setMap(map);
}
}
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
SOLVED! CORRECT CODE!
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<title name="title"></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="cordova-1.6.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '20000',
name: ['whatever']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You're here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
It's hard to give you specific help, because you haven't really described exactly how you are failing. But one thing I notice right away is that you appear to be trying to load the google.maps script twice, with different sensor information in each. In your first google.maps script tag you include the literal text MYAPIKEY which is has to be incorrect. If you had a real key in a variable, I would expect something like:
src="http://maps.googleapis.com/maps/api/js?key=" + MYAPIKEY + "&sensor=true"
And then in your second script tag you appear to load the places library correctly, but then your sensor tag is set as: sensor-false. Your 2nd script tag appears more correct to me, so I would suggest removing the first script tag as a start.
From there, can you provide more detail about how your page is failing and maybe a link to the page?
Some additional observations:
Your initial if-else looks as if it will call the displayPosition function, but the code within displayPosition will not load the google map; it simply creates some vars that then go out of scope when the function ends.
Outside of the displayPosition function, you create a new instance of the google Map, but it references myOptions, which no longer exists at this point in the code, because it only existed within the scope of the displayPosition function.
I would suggest changing the code related to Map creation to something like:
var map = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

Categories

Resources