So, i am trying to create a marker on my google map. In my page html/jsp i have the code of the map where i call a function js : createOfficiel(address, map);
In this function i tried to geocode the string address and create a marker thanks to the geocode. But it doesn't seem to work, can you tell me why ?
Thank you :)
Here is my function .js :
function createOfficiel (address, map){
var address = document.getElementById('address').value;
var officiel = 'images/officiel.png';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({"address": address},
function(results) {
var marqueurOfficiel = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: officiel,
optimized: false
});
});
}
}
well i just find it, the main problem _ i think _ was the position value of the marker. I splited the position in lat + lng.
So here is the code working :
function createOfficiel (address, map){
var officiel = 'images/officiel.png';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
"address": address},
function(results) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var marqueurOfficiel = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
map: map,
icon: officiel,
optimized: false
});
});
}
}
Related
I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>
I'm working with Google Maps API for a project and I'm stuck with this Geociding thing for days...
I need to use geocoding to go in reverse and get the lat and lng from a given address, so I need these functions to create the location points.
var glocations = [];
var locations = [];
var infoWindow = new google.maps.InfoWindow({content: ''});
var geocoder;
var map;
function initMap() {
var center = new google.maps.LatLng(40.6976637,-74.1197637);
var mapOptions = {
zoom: 8,
center: center,
mapTypeControl: false,
fullscreenControl: false,
mapTypeId: google.maps.MapTypeId.TRAFFIC,
styles: []
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder = new google.maps.Geocoder();
locations = [
['0', '','Title', codeAddressLat('brooklyn', '0'), codeAddressLng('brooklyn', '0'), 'category-1', 'https://sat.ptvtelecom.net/img/red.png'],//this doesn't work
['1', '', 'Title', 40.6976637,-74.1197637, 'category-2', 'https://sat.ptvtelecom.net/img/green.png']//this works
];
for (i = 0; i < locations.length; i++) {
var url = locations[i][6];
addMarker(locations[i], url);
}
}
function addMarker(marker, url) {
var category = marker[5];
var title = marker[1];
var pos = new google.maps.LatLng(marker[3], marker[4]);
var content = marker[2];
var icon = {
url: url,
scaledSize: new google.maps.Size(32, 32)
};
marker1 = new google.maps.Marker({
title: title,
icon: icon,
position: pos,
category: category,
map: map
});
glocations.push(marker1);
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
infoWindow.setContent(content);
infoWindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(20);
}
})(marker1, content));
}
function codeAddressLat(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lat = latLng.lat;
if (status == 'OK') {
locations[index][3] = lat;//this will change the lat value, but it won't show on map
//return lat;//this will return undefined lat
}
});
}
function codeAddressLng(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lng = latLng.lng;
if (status == 'OK') {
locations[index][4] = lng;//this will change the lng value, but it won't show on map
//return lng;//this will return undefined lng
}
});
}
initMap();
Okay, so I have three outputs here:
If I write down the lat and long values directly, the location will get the float values and the marker show in the map.
If I manipulate the locations array, the location will get float values and the marker won't show in the map.
If the functions return the values, the location will get undefined values and the marker won't show in the map.
You can see what the output looks like in the following screenshot(just url, I can't post images):
sat.ptvtelecom.net/img/result.png
Any help would be so much appreciate.
google map marker not showing in bootstrap modal.
this is my jquery code :
function map_init() {
if(!$('body').data('map')){
var var_mapoptions = {
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: ['roadmap', 'terrain']
}
};
$('body').data('map',new google.maps.Map($('<div id="map"/>')[0],
var_mapoptions));
}
return $('body').data('map');
}
var Lat;
var lon;
$(document).on('click','a[data-map]',function(){
var data=$(this).data('map'),
map=map_init();
var geocoder = new google.maps.Geocoder();
var address = data;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
Lat = latitude;
lon = longitude;
});
$('#map_modal')
.find('.modal-body')
.append(map.getDiv())
.end()
.find('.modal-title')
.text(data.Name)
.end()
.one('shown.bs.modal',function(){
google.maps.event.trigger(map, "resize");
map.setCenter({lat:Lat,lng:lon});
});
})
.modal('show');
});
it's showing modal , but not showing the map marker. the latitude and longitude values are came from php code( that is from while loop value).
I believe you did not created any Google Maps Javascript API Markers object.
A marker identifies a location on a map. By default, a marker uses a
standard image. Markers can display custom images, in which case they
are usually referred to as "icons."
I would suggest to edit and add this code inside this line:
if ( status == google.maps.GeocoderStatus.OK ) {
//add marker code here
}
code to be added:
var marker = new google.maps.Marker({
positions : new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng() ),
map: map,
title: 'I am a marker :)'
});
And your Marker will appear.
Im trying to use google maps api to convert my address to longitude and latitude and THEN display the map on the page.
Just a note im using PHP/Laravel to retrieve the address from the DB. So although its a hard coded value of new york that will be dynamic after i get this working.
Html
<div id="map" style="height:250px"></div>
Javascript
<script>
var geocoder = new google.maps.Geocoder();
var address = "new york";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude);
}
});
function initMap() {
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap">
</script>
At the moment i'm getting the error of "Uncaught ReferenceError: google is not defined"
Change the order of scripts
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap">
</script>
<script>
var geocoder = new google.maps.Geocoder();
var address = "new york";
// rest of the code
</script>
As mentioned above the code needed to be put inside of my callback function.
<script>
function initMap(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
console.log(latitude);
console.log(longitude);
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCY2buDtbYIot8Llm_FkQXHW36f0Cme6TI&callback=initMap">
</script>
I modified the javascript from https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple to
var geocoder;
var postalArr = [];
postalArr.push(249586);
postalArr.push(266751);
var map;
function initialize(){
var myLatlng = new google.maps.LatLng(1.3667, 103.7500);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
if (postalArr) {
for (var i = 0; i < postalArr.length; i++ ) {
codeAddress(postalArr[i]);
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function codeAddress(postal) {
geocoder.geocode( { 'postal': postal}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
The script goes within the for loop but doesn't run the codeAddress function.
I'm not sure why.
Two things.
(1) need to define geocoder somewhere, I put it in the initialize
function initialize(){
geocoder = new google.maps.Geocoder();
(2) there's no such thing as a postal property to feed the geocoder. Valid requests are for a latlng or an address as explained here.
So at least you must specify a country. I'm not sure what country 249586 is for, in my demo I used two California zip codes, and added ", United States" to the address.
geocoder.geocode( { 'address': postal + ", United States"},