I'm trying to adapt my code with json in google maps. I tried looking at other threads of stackoverflow but did not help me.
How do I show multiple points on the map with the coordinates that are received by json?
This code in firebug shows no errors and the map appears all blue.
var geocoder;
var map;
function initialize() {
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
$.each(data, function(index, c) {
//alert(c.fields['lat']+','+c.fields['lng']); result: -23.0522826,-43.32745712
//Map
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
//options
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
//get the map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//marker
var marker = new google.maps.Marker({
map: map,
position: latlng,
//title: {{i.display.codigo}}
});
//infowindow
var infowindow = new google.maps.InfoWindow({
content: 'oi'
});
//click infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});//close each
});//close getjson
}//close initialize
My response in Json:
[{"pk": 1, "model": "address.coordinates", "fields": {"lat": "-23.0522826", "lng": "-43.32745712"}}, {"pk": 2, "model": "address.coordinates", "fields": {"lat": "-22.24569326", "lng": "-43.7028948"}}]
Thanks!
You have 1 real error here:
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
google.maps.LatLng expects 2 parameters(lat &lng) , but you provide 1(a string containing lat and lng, joined by a comma) . It has to be
latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
But you also have a logical error:
You overwrite the last map created on every each-loop
Create the map and the infoWindow outside of the $.each()
function initialize()
{
var myOptions =
{
zoom: 5,
center: new google.maps.LatLng(1,1) ,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
map= new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds=new google.maps.LatLngBounds();
infowindow = new google.maps.InfoWindow({
content: 'oi'
});
$.each(data, function(index, c) {
var latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+c.pk
});
bounds.extend(latlng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent('pk:'+c.pk);
infowindow.open(map, marker);
});
});//close each
map.fitBounds(bounds);
});//close getjson
}//close initialize
Related
This question already has answers here:
Have just one InfoWindow open in Google Maps API v3
(12 answers)
Closed 5 years ago.
when opening another infowindow the previous ones remain open.
How to automatically close the previous information window if I open another information window? I am something new, can you help me
var map;
var markers = [];
function initMap() {
var cucuta = {lat: 7.9145395, lng: -72.505966};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: cucuta,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
#foreach($users as $user)
var ubicaciones = {lat: {{ $user->latitud }}, lng: {{ $user->longitud }} };
var titulo = '{{ $user->name }}';
addMarker(ubicaciones, titulo);
#endforeach
}
function addMarker(location, titulo) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location),
map: map,
title: titulo
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker) {
return function() {
infowindow.setContent(titulo);
infowindow.open(map, marker);
}
})(marker));
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function showMarkers() {
setMapOnAll(map);
}
I've just tried this in tryit, and it works as expected :
var map;
var infowindow;
function initMap() {
infowindow = new google.maps.InfoWindow();
var cucuta = {lat: 7.9145395, lng: -72.505966};
map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 14,
center: cucuta,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
addMarker({lat: 7.9145395, lng: -72.505966}, 'This is the info of <br>MAP1');
addMarker({lat: 7.9045395, lng: -72.505966}, 'This is the info of <br>MAP2');
}
function addMarker(location, titulo) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location),
map: map,
title: titulo
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(titulo);
infowindow.open(map, marker);
});
}
I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}
Please help. Trying to create a map of Chicago, and have my current known location appear as a marker on that map. The problem is (though I can find no explicit mention of this in any tutorial or doc), it seems I have to declare the marker var in the same scope as (perhaps right after?) I declare the map---global variables don't seem to work. This is difficult, since I'm making an asynchronous call, and thus only have a verified position for my marker in the callback function I've defined. Thus the following code doesn't work...
(function() {
var chicago = new google.maps.LatLng(41.87811, -87.62980);
var info = document.getElementById("info");
var map;
function showError(error)
{
info.innerHTML += "Error: " + error.message;
}
function getLocation(position)
{
current_location = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var marker = new google.maps.Marker({
position: current_location,
map: map
});
}
window.onload = function() {
var mapOptions = {
zoom: 10,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(getLocation, showError);
}
}
})();
I can see no clean way out of this, but would love to be shown otherwise.
If I'm understanding you correctly, than this should work, this is how I handle the asynchronous creation of the marker at the found position in my own app, and it works great! If this isn't what you meant then let me know!
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(lat, lon),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
map = new google.maps.Map(document.getElementById('gmaps'), mapOptions);
locateMe();
}
function locateMe() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
map.setZoom(15);
setMarkerPosition(position.coords.latitude, position.coords.longitude);
updateLocation();
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
}
}
function setMarkerPosition(lati, longi) {
var latLongMarker = new google.maps.LatLng(lati,longi);
marker = new google.maps.Marker({
position: latLongMarker,
map: map,
draggable: false,
title: "Your Location"
});
}
I am having some difficulty with a google map. The problem is that only a small portion of the map is loading as shown here:
After the page loads, if I resize the browser even the slightest amount, this causes the complete map to refresh and load correctly, as shown here:
Here is my javascript code:
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
var $width = document.getElementById("propertysection").offsetWidth;
$('#map-canvas-2').width($width-28-175);
$('#map-canvas-2').height($width);
$('#myGridMap').height($width);
});
function initialize() {
var map;
var propertyMap;
var marker;
var infowindow;
var myOptions = {
zoom: 6,
center:new google.maps.LatLng(50.7,-86.05),
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map-canvas-2"),myOptions);
infowindow = new google.maps.InfoWindow({
content: 'Property Info',
position: new google.maps.LatLng(0, 0)
});
}
Can anyone suggest what the problem might be? Thanks.
You shouldn't mix the jquery ready method with the window load event (see http://api.jquery.com/ready/).
Instead, call initialize from within your .ready function, or place the window resize functions in the initialize method itself (before initializing the map).
I am using bootstrap and a mega menu and I resolved it with using the official Google Maps API asynchronous load function. https://developers.google.com/maps/documentation/javascript/tutorial#asynch
function initialize() {
var myLatLng = new google.maps.LatLng(37.4221147, -122.0867373);
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(37.4221147, -122.0867373),
zoom: 12,
mapTypeControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
var contentString =
'<b>Google Gate Bridge</b>' +
'<p>Mountain View, CA 94043, USA</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(map,marker);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
var tab = document.getElementById('YourHtmlObjectID');
YourHtmlObjectID.onmouseover = loadScript;
YourHtmlObjectID.onclick = loadScript;
I have a little function that adds a marker and info window when it is clicked. However, when I click on a new location, the old one remains. I'd like it to be replaced by the new one. Here is my code:
function MapInitialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(43,-77),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
})
var infowindow = new google.maps.InfoWindow({
content: 'Content Here'
});
infowindow.open(map,marker);
});
}
Thanks!
Delete the old marker before creating the new one:
var marker = null;
function MapInitialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(43,-77),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position: event.latLng,
map: map
})
var infowindow = new google.maps.InfoWindow({
content: 'Content Here'
});
infowindow.open(map,marker);
});
}