I have the ability to create maps and add markers to them at the same time with the following code:
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(39.013421, -94.707803)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);';
geocoder = new google.maps.Geocoder();
var address = "12345 Random Address Dr San Diego, CA";
geocoder.geocode( { 'address': address}, function(results, status) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: "../image/icons/map/icon_marker1.png"
});
});
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
If I try to remove the marker code and call it at a later time I get the error "map is not defined" which at this point it isnt....Is there a correct way to call existing maps? The goal would be to click a button and have something like the following code trigger:
$(".addLayer").click(function(){
//Add Marker Code
geocoder = new google.maps.Geocoder();
var address = "12345 Random Address Dr San Diego, CA";
geocoder.geocode( { 'address': address}, function(results, status) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: "../image/icons/map/icon_marker1.png"
});
});
});
Define your map at the begining of your script. Here the scope of your map var is only your initialize()
function
Edit : here an example
var map = new google.maps.Map(document.getElementById('map-canvas'));';
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(39.013421, -94.707803)
};
map.setOptions(mapOptions)
geocoder = new google.maps.Geocoder();
/* the rest of your code */
}
$(".addLayer").click(function(){
//Add Marker Code
geocoder = new google.maps.Geocoder();
var address = "12345 Random Address Dr San Diego, CA";
geocoder.geocode( { 'address': address}, function(results, status) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: "../image/icons/map/icon_marker1.png"
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.