i have multiple google map instances on my website,now there are two different google map on a same page, what happens is the first one works and other doesn't now i know the logical issue let me show you my code first
<script>
function initMap() {
var myLatLng = {lat: 43.6222102, lng:-79.6694881};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=my_key&callback=initMap"
async defer></script>
now as i defined a callback method it always initializes the method named initMap whereas what i want to do is there can be multiple google maps lets suppose initMap2 how can i load them without callback method?
To load the map without a callback, load the API synchronously/inline (without the async defer), then call your initMap function on the load event.
(Note: FYI: Google changed all their examples to using asynchronous loading to improve the load times)
(Note2: Google has added a "sample" to their documentation describing synchronous loading)
proof of concept fiddle
code snippet:
function initMap() {
var myLatLng = {
lat: 43.6222102,
lng: -79.6694881
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<!-- added 1/21/2023 to prevent:
Loading the Google Maps JavaScript API without a callback is not supported: https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
-->
<script>
function dummy() {}
window.dummy=dummy;
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=dummy"></script>
<div id="map"></div>
Related
What I want to achieve:
I want to display a search box in google map. When a user search a location, result is displayed in map box. On the map, when a user RightClick, I want to store the marker in database.
Resource I tried to implement
storing marker to database:
https://www.sanwebe.com/2013/10/google-map-v3-editing-saving-marker-in-database
displaying search box in map
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
I tried to implement these two as one: here is my minimal code
var mapCenter = new google.maps.LatLng(27.7172, 85.3240);
var map;
google.maps.event.addDomListener(window, 'load', map_initialize);
function map_initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
center: mapCenter,
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'rightclick', function(event) {
create_marker(event.latLng);
});
}
function create_marker(MapPos) {
var marker = new google.maps.Marker({
position: MapPos,
map: map
});
}
#map {
height: 200px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
With this code when I right click on the map, nothing happens i.e. neither the marker shows nor any error.
The map variable needs to be accessible from your create_marker function, therefore you declared it outside of your other functions. But also inside the map_initialize function. Remove the var declaration from there and it will work.
I have edited your original question to include a MCVE which means that I removed 90% of your code to keep only what you were after: adding a marker on right click.
Please take that as a suggestion for how to write your next questions.
var mapCenter = new google.maps.LatLng(27.7172, 85.3240);
google.maps.event.addDomListener(window, 'load', map_initialize);
function map_initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: mapCenter,
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'rightclick', function(event) {
create_marker(event.latLng);
});
}
function create_marker(MapPos) {
var marker = new google.maps.Marker({
position: MapPos,
map: map
});
}
#map {
height: 200px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
I'm using the Google Maps API v3.30 to display multiple GeoJSON map layers. I have declared each layer separately, and I am able to load the GeoJSON, set styles, and switch between each layer without any issue. However when I try to use the forEach method on the declared layer, any code within is not run.
var myLayer = new google.maps.Data();
myLayer.loadGeoJson('Content/Maps/myGeoJsonData.geojson');
myLayer.setStyle( function (feature) {return defaultStyle(feature); });
myLayer.setMap(map);
myLayer.forEach(function (feature) { console.log("Test"); }); // Doesn't work
Everything above works except for the forEach method. I've tried rearranging the order of each line but still the only line that doesn't run is the forEach
loadGeoJson is asynchronous. You need to wait until it completes loading the data from the request before calling .forEach. Use its optional callback function:
from the documentation:
loadGeoJson(url:string, options?:Data.GeoJsonOptions, callback?:function(Array))
Return Value: None
Loads GeoJSON from a URL, and adds the features to the collection.
var myLayer = new google.maps.Data();
myLayer.loadGeoJson(
'Content/Maps/myGeoJsonData.geojson', {},
function(features) {
console.log("loadGeoJson callback "+features.length);
myLayer.forEach(function(feature) {
console.log("Test");
});
});
myLayer.setStyle( function (feature) {return defaultStyle(feature); });
myLayer.setMap(map);
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
zoom: 4,
center: {
lat: -28,
lng: 137
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myLayer = new google.maps.Data();
myLayer.loadGeoJson(
'https://storage.googleapis.com/mapsdevsite/json/google.json', {},
function(features) {
console.log("loadGeoJson callback " + features.length);
myLayer.forEach(function(feature) {
console.log("Test");
});
});
myLayer.setMap(map);
}
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"></script>
<div id="map_canvas"></div>
I am testing Google Maps API and the code who's coming from the doc not working for me, as the marker is not displayed while I have no problem with the map.
function initMap() {
var place = {lat: 48.1389729, lng: -1.935302};
var map = new google.maps.Map(document.getElementById('maps'), {
zoom: 10,
center: place
});
var marker = new google.maps.Marker({
position: place,
map: map,
visible:true,
title: "Hi There",
});
}
The function is created before calling the API with the callback.
What I am missing ?
Add in HTML after you script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
I tried embedding Google Maps javascript API to my website. Tried it local and it worked fine but as soon as i try it on my webserver the tiles wont load.
Heres the simple code im using:
#map { height: 250px; }
<div id="map"></div>
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 49.101670, lng: 9.212140},
zoom: 15
});
var marker = new google.maps.Marker({
position: {lat: 49.101670, lng: 9.212140},
map: map,
title: 'OPTIKHAUS FLEIN'
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrIgqoG8GX88lnjBFX_H_UH6VpK90khSA&callback=initMap">
</script>
Here is how it looks like on the website
Image
even the marker is showing up.
thanks in advance
You have extra spaces in url - js?key. Check my snippet. I update this line "https://maps.googleapis.com/maps/api/js?key=AIzaSyCrIgqoG8GX88lnjBFX_H_UH6VpK90khSA&callback=initMap" only
#map { height: 250px; }
<div id="map"></div>
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 49.101670, lng: 9.212140},
zoom: 15
});
var marker = new google.maps.Marker({
position: {lat: 49.101670, lng: 9.212140},
map: map,
title: 'OPTIKHAUS FLEIN'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrIgqoG8GX88lnjBFX_H_UH6VpK90khSA&callback=initMap">
</script>
I'm clueless as to why this won't run on my mobile browser but it will run on my PC browser, chrome to be exact.
Could any of you provide feedback.
Link to the server I'm testing this on:
54.172.35.180/chat/chatlist.php
<script type="text/javascript">
function success(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here! (at least within a "+position.coords.accuracy+" meter radius)"
});
}
google.maps.event.addDomListener(window, 'load', navigator.geolocation.getCurrentPosition(success));
</script>
I originally just copied and pasted the code from the API site and it worked fine but as soon as I started pulling GPS data it stopped working on my mobile device's browser. Any help would be appreciated.
navigator.geolocation.getCurrentPosition doesn't return a position. So you can't use that result as a parameter of addDomListener(window, ...
What it does, is send a request. When that request is ready, a callback is triggerd. In that callback you can trigger your function success() (I named it initialize).
Just to show what's going on.
You can still choose if this is a good way to proceed.
Feel free to rename, extend, ...
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
function initialize(position, accuracy) {
var latlng = position || new google.maps.LatLng(50.45, 4.45); // set your own default location. This gets called if the parameters are left blank.
var myOptions = {
zoom: 15,
center: latlng
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
if (position) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here! (at least within a " + accuracy + " meter radius)"
});
}
else {
// position of the user not found
}
}
function locationFound(position) {
initialize(
new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
position.coords.accuracy
);
}
function locationNotFound() {
initialize(null, null);
}
function page_loaded() {
// the page is loaded, we can send a request to search for the location of the user
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
}
google.maps.event.addDomListener(window, 'load', page_loaded);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
Probably it's a better idea to first load a map and set a default location.
When the location is found, you change the center and set the marker.
Notice now: if the location is not found, it takes quite a long time before locationNotFound is called